繁体   English   中英

Java RegEx 在每三个空格后拆分

[英]Java RegEx split after every third whitespace

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

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

\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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM