英文:
Java RegEx split after every third whitespace
问题
Let's say I have the String "a 1 b c 2 3 d e f 4 5 6"
and I would like to split it on every third white space to get the substrings "a 1 b"
, "c 2 3"
, "d e f"
, and so on. How would I do that using Regular Expressions? I have tried different variants of "(?=[\\w+][\\s+][\\w+][\\s+][\\w+][\\s+])"
none of which seem to be right. What would be the correct RegEx?
英文:
Let´s say I have the String "a 1 b c 2 3 d e f 4 5 6"
and I would like to split it on every third whitespace to get the substrings "a 1 b"
, " c 2 3"
, " d e f"
, and so on. How would I do that usuing Regular Exprssions? I have tried different variants of "(?=[\\w+][\\s+][\\w+][\\s+][\\w+][\\s+])"
none of which seem to be right. What would be the correct RegEx?
答案1
得分: 3
使用正则表达式模式的模式匹配器:
\S+(?:\s+\S+){0,2}
这将根据您的定义匹配输入中的每个术语:
\S+ 匹配第一个“单词”
(?:
\s+ 空白字符
\S+ 另一个单词
){0,2} 重复零到两次
Java 代码示例:
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]
英文:
Use a pattern matcher with the regex pattern:
<!-- language: regex -->
\S+(?:\s+\S+){0,2}
This will match each term in the input according to your definition:
<!-- language: regex -->
\S+ match first "word"
(?:
\s+ whitespace
\S+ another word
){0,2} zero to two times
<!-- language: java -->
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);
This prints:
<!-- language: none -->
[a 1 b, c 2 3, d e f, 4 5]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论