How to escape a string from regular expression using java

Sometimes when using java you may want to search in a string or split a string using some other string which may have characters which corresponds to special characters in regular expressions. Thus you may want to escape those characters. There are two ways.

1. Escape the special characters one by one.

in this case all you have to do is to put a “\” infront of each special character.

eg: "12+3"  => "12\+3"

2. Escape the whole string at one go.

This asks the regular expression parser to ignore any special characters in the string. This is also very simple as the first method. All you have to do is to put “\Q” in front of the string and “\E” at the end of the string.

eg: "[1] C++ is a (highlevel) programming language" => 
"\Q[1] C++ is a (highlevel) programming language\E"

This is however already available as a function in java

String escapedString=java.util.regex.Pattern.quote(myStringToEscape)

Naturally you can use this method to make parts of a string escape as a regular expression.

Tags: , , , ,

3 Responses to “How to escape a string from regular expression using java”

  1. Tomasz Says:

    Exactly what I was looking for. Thanks!

  2. Isuru Ranawaka Says:

    great solution. thanks!!

  3. Navneet Arora Says:

    Gr8 Nice details, it solved my issue… thanks a lot

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: