我需要捕捉一条线内的重复图案。
例如:
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
。
你能告诉我为什么以及如何解决它?
非常感谢
阿德里安
答案 0 :(得分:1)
您需要此RegEx:(\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*)#?
找到那些。
答案 1 :(得分:0)
试试这段代码:
public static void main(String[] args) {
String s = "toto#titi#tutu#tata#";
Pattern p = Pattern.compile("(\\w{2})(\\1)(?=#)"); // you need too capture the group.
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
}
}
O / P:
toto
titi
tutu
tata
注意:如果字符串为"jfgjd#toto#titi#tutu#tata#sdas";
答案 2 :(得分:0)
public static void main(String[] args) {
String s = "jfgjd#toto#titi#tutu#tata#sdas";
Pattern p = Pattern.compile("(\\w+)(?=#)"); // you need too capture the group.
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
}
}
经过小修改后,你得到了
jfgjd
toto
titi
tutu
tata