woensdag 22 juli 2009

Java regex and String literals

I was just practicing for the SCJP exam and ran into some regex issues. Regex and Java String literals both use "\" as an escape character. In a non-regex Java String literal, every literal "\" must be doubled. In a regex every literal "\" must be doubled. Ok, now lets look at some examples.

When you want to write a pattern to check for a digit followed by a whitespace you need to create the following pattern:

Pattern p = Pattern.compile("\\d\\s"); // here you might expect to use ("\d\s").
Matcher m = p.matcher("12 this should be enough");

Now lets say you want to check for the literal "\" in a String:

String text = "hello in comes the backslash \\ ..."; // mark the double \\ to escape
Pattern p = Pattern.compile("\\\\");
Matcher m = p.matcher(text);

Ofcourse, normally the compiler or IDE helps you with this, by showing something like 'illegal escape character'. But for the exam you really need to 'know' it. 

Geen opmerkingen:

Een reactie posten