replacing exact string in Java assuming it may contain special regex characters

Dhiraj :

I have a String input as well as String pattern and assume they could contain all sort of such characters which have special meaning for regex, and I would like exact word replacement to take place without giving any special consideration to special characters. Any special meaning should be ignored. And I won't know at compile time exactly how many such special characters might be present in either the input string or the input pattern.

So here is the formal problem statement:-

Assume the the object input_string is the input of type String. Then we have another string input_pattern which is also an object of type String.

Now I want to perform the following:-

String result=input_string.replaceFirst(input_pattern,"replacewithsomethingdoesntmatter");

the replacement should take place in 'exact' match manner, without considering any regex special meaning of characters if present in the strings. How to make it happen?

Robby Cornelissen :

You can use the Pattern.quote() method to escape characters that have a special meaning in regular expressions:

String pattern = "^(.*)$";
String quotedPattern = Pattern.quote(pattern);

System.out.println(quotedPattern);

This will wrap the pattern in quotation markers (\Q and \E), indicating that the wrapped sequence needs to be matched literally.

Alternatively, you can wrap the pattern in quotation markers manually:

String pattern = "^(.*)$";
String quotedPattern = "\\Q" + pattern + "\\E";

System.out.println(quotedPattern);

The first approach is probably safer, because it will also make accommodations for expressions that already contain quotation markers.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326291&siteId=1