Sidebar

How do I escape special characters in a regular expression?

0 votes
472 views
asked Feb 4, 2014 by mike-r-7535 (13,830 points)
I am trying to escape a special character inside a regular expression.  In particular, I am trying to replace all open and closing parenthesis in a string.  How do I do this?

1 Answer

0 votes
 
Best answer
With a Java string, you can use replaceAll().  If you have a JavaScript string, you will need to use replace() with the global option (which means do it for all instances).  See this knowledge base article for more information on the difference.
 
In particular, the backslash (\) is the escape character.  When it is in a string, you will need to escape the escape character (use two backslashes).  I would try one of these two approaches...
With Javascript strings (Note in javascript the regular expression is between the two forward slashes (/), and is not surrounded by quotes)
 
str = '' + str;
str.replace(/\(/g, "").replace(/\)/g, "");
 
or with Java strings (Note there are two backslashes for Java, because you need to escape the escape character inside a string.)
 
str = new java.lang.String(str);
str.replaceAll("\\(", "")replaceAll("\\)", "");

 

answered Feb 4, 2014 by mike-r-7535 (13,830 points)
...