Java String replaceAll()The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string. SignatureParametersregex : regular expression replacement : replacement sequence of characters Returnsreplaced string Exception ThrowsPatternSyntaxException: if the syntax of the regular expression is not valid. Internal implementationJava String replaceAll() example: replace characterLet's see an example to replace all the occurrences of a single character. FileName: ReplaceAllExample1.java Test it NowOutput: jevetpoint is e very good website Java String replaceAll() example: replace wordLet's see an example to replace all the occurrences of a single word or set of words. FileName: ReplaceAllExample2.java Test it NowOutput: My name was Khan. My name was Bob. My name was Sonoo. Java String replaceAll() example: remove white spacesLet's see an example to remove all the occurrences of white spaces. FileName: ReplaceAllExample3.java Test it NowOutput: MynameisKhan.MynameisBob.MynameisSonoo. Java String replaceAll() Method Example 4The replaceAll() method throws the PatternSyntaxException when there is an improper regular expression. Look at the following example. FileName: ReplaceAllExample4.java Output: For learning Java, JavaTpoint 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. Java String replaceAll() Method Example 5The replaceAll() method can also be used to insert spaces between characters. FileName: ReplaceAllExample5.java Output: JavaTpoint J a v a T p o i n t Java String replaceAll() Method Example 6Even the null regular expression is also not accepted by the replaceAll() method as the NullPointerException is raised. FileName: ReplaceAllExample6.java Output: JavaTpoint Exception in thread "main" java.lang.NullPointerException at java.base/java.util.regex.Pattern. Next TopicJava String split() |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India