Java String replaceAll()

The java string replaceAll() method returns a string replacing all the sequence of characters matching regular expression and replacement string.

Signature:
public Str replaceAll(String regex, String replacement)
Internal implementation
public String replaceAll(String regex, String replacement) { return Pattern.compile(regex).matcher(this).replaceAll(replacement); }
Parameters

regex : regular expression

replacement : replacement sequence of characters

Returns

replaced string

Example
public class Test { public static void main(String args[]) { String s = "cprogramcoding is a site providing free tutorials"; //remove white spaces String s2 = s.replaceAll("\\s", ""); System.out.println(s2); } }


Output:
cprogramcodingisasiteprovidingfreetutorials
Java String replaceAll() example: replace character

See an example to replace all the occurrences of a single character.

public class Test { public static void main(String args[]) { String str1="cprogramcoding is a very good website"; String re=str1.replaceAll("a","e"); System.out.println(re); } }


Output:
cprogremcoding is e very good website
Java String replaceAll() example: replace word

See an example to replace all the occurrences of single word or set of words.

public class Test { public static void main(String args[]) { String str1="My name is Rama."; String re=str1.replaceAll("is","was"); System.out.println(re); } }


Output:
My name was Rama.
Another Java String replaceAll() example: remove white spaces

See an example to remove all the occurrences of white spaces.

public class Test { public static void main(String args[]) { String str="My name is cprogramcoding."; String re=str.replaceAll("\\s",""); System.out.println(re); } }


Output:
Mynameiscprogramcoding.
Java - String replaceFirst() Method

The method replaces the first substring of the given string which matches that regular expression.

Syntax
public Str replaceFirst(String rgex, String replacement)
Parameters

rgex − the regular expression to which given string need to matched.

replacement − the string that replaces regular expression.

Return Value

This method returns resulting String as an output.

public class Test { public static void main(String args[]) { String str = "This website providing free tutorials"; String str1 = str.replaceFirst("s", "9"); System.out.println(str1); } }


Output:
Thi9 website providing free tutorials



Instagram