Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.replaceAll without RegEx

Tags:

java

I'd like to replace all instances of a substring in a string but String.replaceAll() only accepts a pattern. The string that I have came from a previous match. Is it possible to add escapes to the pattern that I have or is there a version of replaceAll() in another class which accepts a literal string instead of a pattern?

like image 656
dromodel Avatar asked Oct 11 '22 07:10

dromodel


People also ask

Does replaceAll use regex?

replaceAll() The method replaceAll() replaces all occurrences of a String in another String matched by regex. This is similar to the replace() function, the only difference is, that in replaceAll() the String to be replaced is a regex while in replace() it is a String.

Does replaceAll replace original string?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

What is the difference between string replace and replaceAll?

The difference between replace() and replaceAll() method is that the replace() method replaces all the occurrences of old char with new char while replaceAll() method replaces all the occurrences of old string with the new string.


1 Answers

Just use String.replace(CharSequence,CharSequence) rather than replaceAll.

NB: replace doesn't just replace the first occurrence, it replaces all occurrences, like replaceAll.

like image 213
Jon Skeet Avatar answered Oct 12 '22 19:10

Jon Skeet