user548376
user548376

Reputation: 63

Regex matching doesn't work even though the pattern is correct

It's been a few years since I've used regex, but if I remember correctly, the following should work:

String test = "axaxa";
Pattern p = Pattern.compile("([a-c])x\1x\1");
Matcher m = p.matcher(test);

m matches nothing on run. This is a super simplified version of what I'm doing in my code. That example is actually taken from a Java tutorial on regex! I tried to rewrite my html matching code from way back when it didn't work, I went to researching, thinking I did something wrong... which according to the Internet, I haven't. So. Does anyone have a clue as to why this doesn't work?

Extra info, test.matches(the_pattern) returns false. It seems like the group backtracking is messing it up.

Upvotes: 2

Views: 165

Answers (2)

codaddict
codaddict

Reputation: 455010

Try using \\1 in pace of \1.

\ is the escape character in Java string. To send a \1 to regex engine, we need to escape the \ as \\1.

Upvotes: 3

Andreas Dolk
Andreas Dolk

Reputation: 114767

In Java we have to escape the backslashes:

Pattern p = Pattern.compile("([a-c])x\\1x\\1");

Upvotes: 1

Related Questions