如何使用Java Regex查找字符串中所有重复的字符序列? [英] How do I use Java Regex to find all repeating character sequences in a string?

查看:35
本文介绍了如何使用Java Regex查找字符串中所有重复的字符序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Parsing a random string looking for repeating sequences using Java and Regex.

考虑字符串:

aaabbaaacccbb

aaabbaaacccbb

我想找到一个能找到上述字符串中所有匹配项的正则表达式:

I'd like to find a regular expression that will find all the matches in the above string:

aaabbaaacccbb
^^^  ^^^

aaabbaaacccbb
   ^^      ^^

什么是正则表达式,它将检查字符串中是否有重复的字符序列,并返回这些重复字符的组,使得组1 = aaa和组2 = bb.还要注意,我已经使用了示例字符串,但是任何重复的字符都是有效的:罗恩·乔·乔... 、、、、、 ...,

What is the regex expression that will check a string for any repeating sequences of characters and return the groups of those repeating characters such that group 1 = aaa and group 2 = bb. Also note that I've used an example string but any repeating characters are valid: 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());
        }
    }
}

输出:

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

这篇关于如何使用Java Regex查找字符串中所有重复的字符序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆