10

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

考虑字符串:

啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊

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

aaabbaaacccbb
^^^  ^^^

aaabbaaacccbb
   ^^      ^^

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

4

5 回答 5

9

这样做:

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());
        }
    }
}

输出:

aaa
bb
aaa
ccc
bb
RonRonRon
JoeJoe
....
,,,,
---
于 2012-04-23T20:34:19.847 回答
3

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

我将它设置为仅返回至少 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));
    }
  }
}

输出:
罗恩·
萨姆
·乔

于 2012-04-23T21:16:30.910 回答
2

您可以使用这个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));

输出:

Group # 1 got: aaa
Group # 2 got: bb
于 2012-04-23T20:32:39.957 回答
0

您可以忽略重叠。

// 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
于 2012-04-23T23:02:09.447 回答
0

这似乎有效,尽管它也给出了子序列:

(公平地说,这是根据 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);
    }
}
于 2012-04-23T20:56:44.683 回答