java - 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+])"
但似乎没有一个是正确的。什么是正确的正则表达式?
解决方案
使用带有正则表达式模式的模式匹配器:
\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]
推荐阅读
- apache-kafka - kafka多消费群体
- unity3d - 为什么不显示第二个材料?
- c# - 名称、街道名称、城市名称等的正则表达式
- c++ - 数组中保留的 2 个集合的差异 - C++
- typescript - Angular 6.x Typescript 错误 - 找不到名称“地图”或“可迭代”
- python - Flask-Security,在蓝图中实现 SECURITY_TRACKABLE 功能
- angular6 - NgRx 存储列表和详细数据对象
- javascript - React Native - 返回上一页时如何刷新 FlatList?
- grafana - Istio 1.0.2 在浏览器上访问 grafana
- javascript - 按特定顺序将 JavaScript 对象分组到数组中