java regex illegal escape character error not occurring from command line arguments
- by Shades88
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?