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)

ex.
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);
System.out.println(mat.replaceAll("your")); 
mat.reset();
The output will be "This is your string"

8 comments:

eamon 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.

Kate
http://educationonline-101.com

SUHAS said...

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

Regards,
Suhas

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 Dalisay 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.

Toys Exporters said...
This comment has been removed by the author.
Peterdell said...

Thank you !!

List of Java books

Toys Exporters 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.

Related Posts with Thumbnails