Home > Back-end >  How to check if two characters occur with equal frequency consecutively in a string [closed]
How to check if two characters occur with equal frequency consecutively in a string [closed]

Time:10-01

I wish to write a regular expression which matches strings which are of the type for example "aaabbb" or "aabb" (without quotes) or in other words 'a' and 'b' occur with equal frequency consecutively(not necessarily 2 or 3, it was just an example in the above line). Any leads would be really helpful.

CodePudding user response:

Well, this is as close as I could come. I had to use the String length method to compare the two groups. But it doesn't completely rely on a single regular expression.

Pattern p = Pattern.compile("((.)\\2*)(?!\\2)((.)\\4*)");
for (String s : new String[] { "aabb", "rrrsss", "AAABBBB",
        "AB", "qqqqzzzz" }) {
    Matcher m = p.matcher(s);
    System.out.println(s   ": "   (m.find()
            && m.group(1).length() == m.group(3).length()));
}

prints

aabb: true
rrrsss: true
AAABBBB: false
AB: true
qqqqzzzz: true

  • Related