Home » Java String replaceAll() method

Java String replaceAll() method

by Online Tutorials Library

Java String replaceAll()

The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.

Signature

Parameters

regex : regular expression

replacement : replacement sequence of characters

Returns

replaced string

Exception Throws

PatternSyntaxException: if the syntax of the regular expression is not valid.

Internal implementation

Java String replaceAll() example: replace character

Let’s see an example to replace all the occurrences of a single character.

FileName: ReplaceAllExample1.java

Test it Now

Output:

jevetpoint is e very good website  

Java String replaceAll() example: replace word

Let’s see an example to replace all the occurrences of a single word or set of words.

FileName: ReplaceAllExample2.java

Test it Now

Output:

My name was Khan. My name was Bob. My name was Tutoraspire.  

Java String replaceAll() example: remove white spaces

Let’s see an example to remove all the occurrences of white spaces.

FileName: ReplaceAllExample3.java

Test it Now

Output:

MynameisKhan.MynameisBob.Mynameisamitsingh.  

Java String replaceAll() Method Example 4

The replaceAll() method throws the PatternSyntaxException when there is an improper regular expression. Look at the following example.

FileName: ReplaceAllExample4.java

Output:

For learning Java, TutorAspire is a very good site.    Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1    at java.base/java.util.regex.Pattern.error(Pattern.java:2015)  at java.base/java.util.regex.Pattern.compile(Pattern.java:1784)  at java.base/java.util.regex.Pattern.(Pattern.java:1427)  at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)  at java.base/java.lang.String.replaceAll(String.java:2126)  at ReplaceExample4.main(ReplaceExample4.java:12)  

Java String replaceAll() Method Example 5

The replaceAll() method can also be used to insert spaces between characters.

FileName: ReplaceAllExample5.java

Output:

TutorAspire   J a v a T p o i n t  

Java String replaceAll() Method Example 6

Even the null regular expression is also not accepted by the replaceAll() method as the NullPointerException is raised.

FileName: ReplaceAllExample6.java

Output:

TutorAspire    Exception in thread "main" java.lang.NullPointerException  at java.base/java.util.regex.Pattern.(Pattern.java:1426)  at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)  at java.base/java.lang.String.replaceAll(String.java:2126)  at ReplaceAllExample6.main(ReplaceAllExample6.java:13)  

You may also like