根据正则表达式拆分数组 [英] Split an array based on regex

查看:98
本文介绍了根据正则表达式拆分数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是一个愚蠢的问题,因为我是Java新手.

Sorry if this is a stupid question, as I am new to Java.

如果我有一个像这样的数组

If I have an array like

{ "A123","blue","A456","red","green",
  "B111","purple","C444","blue","green","yellow","pink" }

如何将其拆分为较小的数组,其中第一个元素应为字母,后跟3个数字?例如,输出为:

how can I split this into smaller arrays where the first element should be a letter followed by 3 numbers? For example, the output would be:

{ {"A123","blue"},{"A456","red","green"},
  {"B111","purple"},{"C444","blue","green","yellow","pink"} }

模式 [A-Z] [0-9] {3} 之后可以包含任意数量的元素,直到下次出现该模式为止.

The pattern [A-Z][0-9]{3} could have any number of element after it up until the next occurrence of the pattern.

推荐答案

您可以从此数组中收集地图:

You can collect a map from this array:

String[] arr = {"A123", "blue", "A456", "red", "green",
        "B111", "purple", "C444", "blue", "green", "yellow", "pink"};

Map<String, List<String>> map = new LinkedHashMap<>();

// assume that first is the 'primary' element
List<String> list = null;
for (String str : arr) {
    // if this is a 'primary' element
    // regex:
    // \\D{1} - first character is non-digit
    // \\d+   - non-empty sequence of digits
    if (str.matches("\\D{1}\\d+")) {
        // put new entry into the map and initialise new list
        list = map.computeIfAbsent(str, el -> new ArrayList<>());
    } else {
        // otherwise, add the 'secondary' element to the list
        list.add(str);
    }
}

// output
map.forEach((k, v) -> System.out.println(k + "=" + v));
//A123=[blue]
//A456=[red, green]
//B111=[purple]
//C444=[blue, green, yellow, pink]


// convert a map to a 2d array, if needed
String[][] arr2d = map.entrySet().stream()
        .map(entry -> Stream
                .concat(Stream.of(entry.getKey()), entry.getValue().stream())
                .toArray(String[]::new))
        .toArray(String[][]::new);

// output
Arrays.stream(arr2d).map(Arrays::toString).forEach(System.out::println);
//[A123, blue]
//[A456, red, green]
//[B111, purple]
//[C444, blue, green, yellow, pink]

这篇关于根据正则表达式拆分数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆