6/12/07

backslash, regex and replaceAll function in java

The Java String class has several methods that allow you to perform an operation using a regular expression on that string. One is replaceAll(String regex, String replacement) that take strings as arguments. Java string use the literal string "\\" for single backslash and in regular expression, the "\\" matches a single backslash too. This make [the regular expression as java string] single backslash becomes "\\\\". e.g. If you have a string "c:\test\test2\" and want to change to "c:/test/test2/", your code should look like

class Bsl{ 
public static void main(String args[]){
String s="c:\\test\\test2";
String foreslash="/";
String regex="\\\\";
System.out.println(s.replaceAll(regex,foreslash));
}
}

result:
[poj@mail cronprog]$ java Bsl
c:/test/test2
[poj@mail cronprog]$

another example: the string "$" must be "\$" for java and again "\\$" for regex. So to change "$" to "/" .
class DS{
public static void main(String args[]){
String foreslash="/";
String ds="150$";
System.out.println(ds);
System.out.println(ds.replaceAll("$",foreslash));
System.out.println(ds.replaceAll("\\$",foreslash));
}
}

result:
[poj@mail cronprog]$ java DS
150$
150$/
150/
[poj@mail cronprog]$

note that the regex "$" will not work.

1 comments:

Anonymous said...

Many Thanks :D