Earlier today I was helping out on a regex problem ( http://forum.java.sun.com/thread.jspa?threadID=5256437&tstart=0 ) when I came across a problem with regex 'look behind'.
Given the string "36,1, XX YYYYYYYYY" I am trying to match with look behind the "36,1," and then replace the bit that follows it. What I expected to be able to use was
"(?<=^\\d+,\\d+,)"
but this failed. If it had failed with a
"Exception in thread "main" java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index ...{code}
then I would have just kicked myself for falling for the same trap again. BUT, there was no error, just a failure to match.
A small change to the regex {code}
"(?<=^\\d+,\\d,)"{code}
which only allows a single digit as the second integer works fine.
I have tried various other regex that should be equivalent to my first and the only other one to work is{code}
"(?<=^\\d+,\\d\\d?,)"{code}
Am I missing something?
Test harness :
{code}
public class Sabre080122
{
public static void main(final String[] args)
{
{
final String line = "36,1, XX YYYYYYYYY";
// Looking for the line to start with \\d+,\\d+,
System.out.println(line.replaceFirst("(?<=^\\d+,\\d,)\\s+([^ ]+)", "$1,"));
System.out.println(line.replaceFirst("(?<=^\\d+,\\d+,)\\s+([^ ]+)", "$1,"));
System.out.println(line.replaceFirst("(?<=^\\d+,\\d{1,},)\\s+([^ ]+)", "$1,"));
System.out.println(line.replaceFirst("(?<=^\\d+,\\d\\d*,)\\s+([^ ]+)", "$1,"));
System.out.println(line.replaceFirst("(?<=^\\d+,\\d\\d?,)\\s+([^ ]+)", "$1,"));
}
}
}
{code}
JDK1.6.0_03 on Ubuntu 7.10 .