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:

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

    Regards,
    Suhas

    ReplyDelete
  2. 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....

    ReplyDelete
  3. Nice blog, thanks for this. :)

    ReplyDelete
  4. 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.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. 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.

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

    ReplyDelete