首页 > 解决方案 > Java RegEx 在每三个空格后拆分

问题描述

假设我有字符串"a 1 b c 2 3 d e f 4 5 6",我想每隔三个空格将其拆分,以获得子字符串"a 1 b"" c 2 3"" d e f"等。我将如何使用正则表达式来做到这一点?我尝试了不同的变体,"(?=[\\w+][\\s+][\\w+][\\s+][\\w+][\\s+])"但似乎没有一个是正确的。什么是正确的正则表达式?

标签: javaregex

解决方案


使用带有正则表达式模式的模式匹配器:

\S+(?:\s+\S+){0,2}

这将根据您的定义匹配输入中的每个术语:

\S+    match first "word"
(?:
    \s+  whitespace
    \S+  another word
){0,2}   zero to two times
String input = "a 1 b c 2 3 d e f 4 5 ";
String pattern = "\\S+(?:\\s+\\S+){0,2}";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
List<String> matches = new ArrayList<>();

while (m.find()) {
    matches.add(m.group(0));
}

System.out.println(matches);

这打印:

[a 1 b, c 2 3, d e f, 4 5]

推荐阅读