Java正则表达式在每三个空格后拆分

huangapple go评论75阅读模式
英文:

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 &quot;word&quot;
(?:
    \s+  whitespace
    \S+  another word
){0,2}   zero to two times

<!-- language: java -->

String input = &quot;a 1 b c 2 3 d e f 4 5 &quot;;
String pattern = &quot;\\S+(?:\\s+\\S+){0,2}&quot;;
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
List&lt;String&gt; matches = new ArrayList&lt;&gt;();

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]

huangapple
  • 本文由 发表于 2020年10月17日 20:59:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64402737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定