如何检查一定数量的给定字符
How to check for a certain number of a given character
我正在尝试在 Java 中使用正则表达式在给定数量的“,”之后拆分字符串
假设我有:
“1、2、3、4、5、6、7、8、9、10”
我想在第 5 个“,”处拆分字符串,这样做的正则表达式是什么?
预期结果:
“1、2、3、4、5”
“6、7、8、9、10”
我试过使用“.{30}”,但这很重要而且不合适。并且使用"\\d{30}"在第30位后不拆分。
谢谢!
您可以使用此正则表达式进行匹配:
(?:\d+, *){4}\d+
RegEx Demo
这会给你 2 个匹配项:
1, 2, 3, 4, 5
6, 7, 8, 9, 10
代码:
String s = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15";
Pattern pat = Pattern.compile("(?:\d+, *){4}\d+");
Matcher mat = pat.matcher(s);
StringBuilder output = new StringBuilder();
while(mat.find()) {
output.append(mat.group()).append("\n");
}
System.out.print(output);
输出:
1, 2, 3, 4, 5
6, 7, 8, 9, 10
11, 12, 13, 14, 15
如果您不需要验证输入,那么您可以使用此正则表达式匹配 5 个数字的组(最后一个除外,它可以有 1 到 4 个数字)。
假设输入有效,当前面有 5 个数字时,正则表达式将始终匹配所有 5 个数字,因此它唯一可以匹配较少的情况是可用数字少于 5 个时。
Matcher m = Pattern.compile("\d+(?: *, *\d+){0,4}").matcher(input);
while (m.find()) {
System.out.println(m.group());
}
给定输入 "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11"
,它输出:
1, 2, 3, 4, 5
6, 7, 8, 9, 10
11
(无前导或尾随 space)
如果要同时验证和提取结果,正则表达式会更复杂。
1 个匹配项使用组捕获部分的示例:
((?:\d+\,\s*){4}\d+),\s*(.+)
在带有 perl 的 shellscript 中的用法:
$ echo '1, 2, 3, 4, 5, 6, 7, 8, 9, 10' | perl -p -e 's/((?:\d+\,\s*){4}\d+),\s*(.+)/One: [], Another: []/'
One: [1, 2, 3, 4, 5], Another: [6, 7, 8, 9, 10]
https://regex101.com/r/hL0eH7/2
但我不会为此使用正则表达式,通常你最好使用编程语言的字符串处理函数。
我正在尝试在 Java 中使用正则表达式在给定数量的“,”之后拆分字符串
假设我有:
“1、2、3、4、5、6、7、8、9、10”
我想在第 5 个“,”处拆分字符串,这样做的正则表达式是什么?
预期结果:
“1、2、3、4、5” “6、7、8、9、10”
我试过使用“.{30}”,但这很重要而且不合适。并且使用"\\d{30}"在第30位后不拆分。
谢谢!
您可以使用此正则表达式进行匹配:
(?:\d+, *){4}\d+
RegEx Demo
这会给你 2 个匹配项:
1, 2, 3, 4, 5
6, 7, 8, 9, 10
代码:
String s = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15";
Pattern pat = Pattern.compile("(?:\d+, *){4}\d+");
Matcher mat = pat.matcher(s);
StringBuilder output = new StringBuilder();
while(mat.find()) {
output.append(mat.group()).append("\n");
}
System.out.print(output);
输出:
1, 2, 3, 4, 5
6, 7, 8, 9, 10
11, 12, 13, 14, 15
如果您不需要验证输入,那么您可以使用此正则表达式匹配 5 个数字的组(最后一个除外,它可以有 1 到 4 个数字)。
假设输入有效,当前面有 5 个数字时,正则表达式将始终匹配所有 5 个数字,因此它唯一可以匹配较少的情况是可用数字少于 5 个时。
Matcher m = Pattern.compile("\d+(?: *, *\d+){0,4}").matcher(input);
while (m.find()) {
System.out.println(m.group());
}
给定输入 "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11"
,它输出:
1, 2, 3, 4, 5
6, 7, 8, 9, 10
11
(无前导或尾随 space)
如果要同时验证和提取结果,正则表达式会更复杂。
1 个匹配项使用组捕获部分的示例:
((?:\d+\,\s*){4}\d+),\s*(.+)
在带有 perl 的 shellscript 中的用法:
$ echo '1, 2, 3, 4, 5, 6, 7, 8, 9, 10' | perl -p -e 's/((?:\d+\,\s*){4}\d+),\s*(.+)/One: [], Another: []/'
One: [1, 2, 3, 4, 5], Another: [6, 7, 8, 9, 10]
https://regex101.com/r/hL0eH7/2
但我不会为此使用正则表达式,通常你最好使用编程语言的字符串处理函数。