我需要捕获一行内的重复模式。
例如:
toto#titi#
或 toto#titi#tutu
或 toto#titi#tutu#tata#
等...
这是我的正则表达式:(?:[\w]*#){1,}
我需要捕捉 toto、titi、tutu...
但即使 Matcher.matches()
返回 true,我拥有的唯一组就是最后捕获的模式:
toto#titi#
-> 1 组 titi
、toto#titi#tutu
-> 1 组tutu
、toto#titi#tutu#tata
-> 1 组tata
。
您能告诉我原因以及如何解决吗?
非常感谢
艾德里安
最佳答案
您将需要这个正则表达式:(\w+)#?
并通过
Pattern pattern = Pattern.compile("(\\w+)#?");
Pattern check = Pattern.compile("^[\\w#]+$");
if (!check.matcher(input).matches()) // As requested: Sanity check
throw new IllegalArgumentException("Bogus input received :(");
Matcher m = pattern.matcher(input);
while (m.find()) {
String matched = m.group(1); // Iterates over the occurences
System.out.println("I found " + matched);
}
tata#titi#tutu
的输出:
I found tata
I found titi
I found tutu
并不是在如此简单的情况下代码,
for (String matched : input.split("#"))
System.out.println("I found " + matched);
本质上是等价的。因此,您不必在这里使用 RegEx。
本质上等效,我的意思是 String.split("#")
将从输入中为您提供空的 String
,如 #tata#titi##tutu
(这里总共 2 个),而正则表达式需要更改为 (\w*)#?
才能找到这些内容。
关于java - 重复捕获组与捕获重复组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24936169/