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"

9 comments:

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

periyannan said...

I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..

evs full form
raw agent full form
full form of tbh in instagram
dbs bank full form
https full form
tft full form
pco full form
kra full form in hr
tbh full form in instagram story
epc full form

thatey said...

cheap designer bags replica a59 u3t75g6j26 Louis Vuitton replica Bags t21 s1x78a5e16 high quality designer replica i34 p3s00t0u15

Related Posts with Thumbnails