Anonymous
Anonymous

Reputation: 962

Regex not working in Java code although it works on regex websites

I guess I am just too tired, but I cannot figure it out after reading all the docs and tutorials. I have the following code:

import java.util.regex.*;

class Main {
  public static void main(String args[]) {
    String str = "ababaaabaaaaaabbbbbbaaaaaabaabababababaaaaaabbbbbbaaaaaabababababaaaaaabbbbbbaaaaaa";
    Pattern regex = Pattern.compile("(([ab])\2{5})(?!\1)(([ab])\4{5})(?!\3)(([ab])\6{5})");
    Matcher matcher = regex.matcher(str);

    int counter666 = 0;
    while (matcher.find()) ++counter666;
    System.out.println(counter666);
  }
}

I want to search the string for six occurrences of the same letter (should be a or b) three times after each other (but not three times the same letter). So, these are the only possible matches:

This regex is working on regex101 and on this page. However, my code always returns zero instead of three. Is there any option I have to set to make it working?

Upvotes: 0

Views: 48

Answers (2)

Srdjan M.
Srdjan M.

Reputation: 3405

Shorter version with less steps and two groups.

([ab])\1{5}(?!\1)([ab])\2{5}(?!\2)[ab]{6}

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201467

You're very very close. In order for the regular expression to work in a Java String you have to escape the \ literals; otherwise the compiler doesn't put the value in the String (that you expect anyway). Like,

Pattern regex = Pattern.compile(
        "(([ab])\\2{5})(?!\\1)(([ab])\\4{5})(?!\\3)(([ab])\\6{5})");

And I get (with no other changes)

3

Upvotes: 6

Related Questions