tags:

views:

76

answers:

2

Hi all,

I am trying to use back references in Java regex, but it seems I'm not doing it the right way and can't get it work. I wanted to be able to match parts of string surrounded by 2 same quotes, say find if a string contains "whatever" or 'whatever'.

I then wrote the following code :

Pattern p = Pattern.compile("(\"|\')whatever\1");
Matcher m = p.matcher("'whatever'loremipsumblah");
System.out.println(m.find());   // always returns false

... but it seems the back reference is not working at all, as the matcher can't find any part of the string matching the pattern. I hope you guys will be able to help me cause I'm definitely stuck :|

+3  A: 

Escape the backslash before the digit '1'. Otherwise the sequence "\1" is interpreted as an octal escape for the character U+0001.

Pattern p = Pattern.compile("(\"|\')whatever\\1");
erickson
I forgot it, don't know why, thought it would result in "\" char followed by one... Thanks for pointing my foolishness !
LePad
Unlike some languages, Java treats an unknown escape in a String literal as a syntax error. So a literal '\' character in a String must always be escaped.
Stephen C
A: 

Maybe you should try "lookingAt" instead of "find". Something like this:

Pattern p = Pattern.compile("(\"|\')whatever\\1");
Matcher m = p.matcher("\"whatever\"");

if (m.lookingAt())
    System.out.println(m.group());
Satyajit