Thursday, September 26, 2013

Java regular expression: anchored versus unanchored greedy quantifier

Here's a simple Java program

$ cat Test.java
class Test
{
    public static void main (String args[])
    {
        System.out.println ("this".replaceAll (".*", "that"));
        System.out.println ("this".replaceAll ("^.*$", "that"));
    }
}

When compiled and run, it produces

$ javac Test.java
$ java Test
thatthat
that

What's up with that first replacement? Why is the "that" doubled? Beats me...

$ java -version
java version "1.6.0_51"
Java(TM) SE Runtime Environment (build 1.6.0_51-b11-456-11M4508)
Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-456, mixed mode)

No comments: