Alex Hughes || microfeeds:

You can have them fresh on your plate everyday using your favourite feed reader: 'http://microfeed.ahughes.org/feed.php'

Special thanks to my friend and colleague Karen for the 5 minute godly touches on my horrible CSS file.

 

Java replace() and replaceAll() methods

When handling simple strings in Java, chances are that somebody will need to perform a search and replace operation.

There is a rookie mistake one can make (even if he's not a rookie anymore) using the wrong function for the wrong task, mainly because of the unusual naming convention.

For instance, today, I stumbled upon a piece of code that was using the replaceAll() function, even though this was not necessary because it could be using the replace() function instead.

What is the harm though?

The harm was that because of that, the code was buggy and was occasionally throwing the following exception:

java.lang.IndexOutOfBoundsException: No group 1 | Pattern matching

All of this, was happening because some symbols of the text were not escaped properly, and the compiler thought that I was trying to use a regular expression.

So, the million dollar question is, what is the difference between replace() and replaceAll()?

The replaceAll() and replaceFirst() are functions that use regular expressions. The replace() function DOES NOT.

This means that replaceAll() replaces all occurences, using regex. Consider it like a helper for using regex in a certain way. The replace() function, again replaces ALL, even though its name does not imply so, without using regex.

Because of the above fact, the replaceAll() needs some characters to be escaped in the supplied String, otherwise they will be mistaken for a regex, throwing various annoying exceptions.

So, if all you need to do is a simple find and replace operation without messing with regex, use replace(). It is slightly faster and a lot more foolproof.

 

Further reading here, here and here.

Documentation for the replace() here

Documentation for the replaceAll() here

 

Mon Nov 24th, 21:34:02 Greenwich Mean Time (GMT)

More Feeds

Microfeed is proudly powered by Microfeed. MicrofeedCeption.