如何使用Java Regex查找字符串中的所有重复字符序列?

使用Java和Regex解析随机字符串以查找重复序列。

考虑字符串:

aaabbaaacccbb

我想找到一个正则表达式,它将在上面的字符串中找到所有匹配项:

aaabbaaacccbb ^^^ ^^^ aaabbaaacccbb ^^ ^^ 

什么是正则表达式,它将检查字符串是否有任何重复的字符序列,并返回那些重复字符的组,使得组1 = aaa和组2 = bb。 另请注意,我使用了一个示例字符串,但任何重复的字符都是有效的:RonRonJoeJoe …… … ,, … ,,

这样做:

 import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String s = "aaabbaaacccbb"; find(s); String s1 = "RonRonRonJoeJoe .... ,,,,"; find(s1); System.err.println("---"); String s2 = "RonBobRonJoe"; find(s2); } private static void find(String s) { Matcher m = Pattern.compile("(.+)\\1+").matcher(s); while (m.find()) { System.err.println(m.group()); } } } 

OUTPUT:

 aaa bb aaa ccc bb RonRonRon JoeJoe .... ,,,, --- 

以下内容适用于所有要求。 它实际上是这里的几个答案的组合,它将打印出在字符串中任何其他位置重复的所有子字符串。

我将其设置为仅返回至少2个字符的子字符串,但通过将正则表达式中的“{2,}”更改为“+”,可以轻松将其更改为单个字符。

 public static void main(String[] args) { String s = "RonSamJoeJoeSamRon"; Matcher m = Pattern.compile("(\\S{2,})(?=.*?\\1)").matcher(s); while (m.find()) { for (int i = 1; i <= m.groupCount(); i++) { System.out.println(m.group(i)); } } } 

输出:
罗恩
山姆

你可以使用这个positive lookahead正则表达式:

 ((\\w)\\2+)(?=.*\\1) 

码:

 String elem = "aaabbaaacccbb"; String regex = "((\\w)\\2+)(?=.*\\1)"; Pattern p = Pattern.compile(regex); Matcher matcher = p.matcher(elem); for (int i=1; matcher.find(); i++) System.out.println("Group # " + i + " got: " + matcher.group(1)); 

OUTPUT:

 Group # 1 got: aaa Group # 2 got: bb 

这似乎有效,但它也给出了后续的结果:

(公平地说,这是基于Guillame的代码)

 public static void main(final String[] args) { // final String s = "RonRonJoeJoe"; // final String s = "RonBobRonJoe"; final String s = "aaabbaaacccbb"; final Pattern p = Pattern.compile("(.+).*\\1"); final Matcher m = p.matcher(s); int start = 0; while (m.find(start)) { System.out.println(m.group(1)); start = m.toMatchResult().end(1); } } 

你可以忽略重叠。

 // overlapped 1 or more chars (?=(\w{1,}).*\1) // overlapped 2 or more chars (?=(\w{2,}).*\1) // overlapped 3 or more chars, etc .. (?=(\w{3,}).*\1) 

或者,你可以消费(非重叠)..

 // 1 or more chars (?=(\w{1,}).*\1) \1 // 2 or more chars (?=(\w{2,}).*\1) \1 // 3 or more chars, etc .. (?=(\w{3,}).*\1) \1