Saturday, November 01, 2008

How to Replace Strings in Java - Using java.util.regex package

Replacing a charater in a String is just a matter of adding a one line to the code.

originalString.replace(oldChar, newChar)

String originalString = "This/is/my/string";
System.out.println(originalString.replace('/', '|'));
Then the output will be "This|is|my|string"

Anyway how can we replace a character or number of characters(a substring) with another string. This can be done using the regex package in Java.

If we need to replace "my" with "your" we can do it in the following way.
import java.util.regex.*;  

String originalString = "This is my string";
Pattern pat = Pattern.compile("my"); 
Matcher mat = pat.matcher(originalString);
The output will be "This is your string"


Anonymous said...

I recently came accross your blog and have been reading along. I thought I would leave my first comment. I dont know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.


Unknown said...

very well, thanks for this, this explanation provide me lot of help. I am new to java.


Dinuka Arseculeratne said...

but String object already has a replace all method. Why would we need to go through all the hassle of creating a Pattern and compiling it etc etc....

Mike said...

Nice blog, thanks for this. :)

javin paul said...

Nice post kalani, You indeed covered it nicely. By the way when we replace String it generate a new String because String is immutable. I have also shared few tips on replacing string in Java. let me know how do you find it.

Thomas Morgan said...
This comment has been removed by the author.
Peterdell said...

Thank you !!

List of Java books

Thomas Morgan said...

You can very easily lean here how to replace string in java that is not easy job so must share it with others by the use of research paper writing. Because this kind of information is very difficult to get for other people so do this good job and share it well.

Pawel Co Faddey said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

Related Posts with Thumbnails