java regex illegal escape character error not occurring from command line arguments

Posted by Shades88 on Stack Overflow See other posts from Stack Overflow or by Shades88
Published on 2012-09-24T21:33:24Z Indexed on 2012/09/24 21:37 UTC
Read the original article Hit count: 429

Filed under:
|

This simple regex program

import java.util.regex.*;
class Regex {
    public static void main(String [] args) {
        System.out.println(args[0]); // #1
        Pattern p = Pattern.compile(args[0]); // #2
        Matcher m = p.matcher(args[1]);
        boolean b = false;
        while(b = m.find()) {
            System.out.println(m.start()+" "+m.group());
        }
    }
}

invoked by java regex "\d" "sfdd1" compiles and runs fine.

But if #1 is replaced by Pattern p = Pattern.compile("\d");, it gives compiler error saying illegal escape character. In #1 I also tried printing the pattern specified in the command line arguments. It prints \d, which means it is just getting replaced by \d in #2.

So then why won't it throw any exception? At the end it's string argument that Pattern.compile() is taking, doesn't it detect illegal escape character then? Can someone please explain why is this behaviour?

© Stack Overflow or respective owner

Related posts about java

Related posts about regex