Java String replaceFirst()
1. Overview
In this String API Methods series, You'll learn replaceFirst() method of String class.
Replaces the first substring of this string that matches the given regular expression with the given replacement.This method is mostly useful when you want to do the changes only for the first found value and not for all values. But, replace() method replaces for all matches with the given string. You must be careful and choose the right one for your use-case.
- replace() for characters replacing
- replaceAll() for replacing strings.
2. Java String replaceFirst() Syntax
Syntax:
public String replaceFirst(String regex, String replacement)
Parameters:
regex - the regular expression to which this string is to be matched
replacement - the string to be substituted for the first match
3. Java String replaceFirst() Example
The below program string has a "BOSS" word two times but we want to replace only the first match with the "Boss" word. Let us run the program and see how it produces the output.
Java String replaceFirst() Example
package com.javaprogramto.strings;public class StringReplaceFirstExample {public static void main(String[] args) {String str = "Hello BOSS, Welcome to JavaProgramTo.com SUPER-BOSS";String replacedString = str.replaceFirst("BOSS", "Boss");System.out.println("Output of replaceFirst() method : " + replacedString);}}
Output:
Output of replaceFirst() method : Hello Boss, Welcome to JavaProgramTo.com SUPER-BOSS
Yes, your guess is right. It just replaced the first match case and not the other matches.
4. Java String replaceFirst() Example with Special Characters
Next, let us work with special characters such as $ or / symbols whether works will replaceFirst() method.
In the below code, trying to replace the "$$" with Dollars word.
package com.javaprogramto.strings;public class StringReplaceFirstSpecialCharsExample {public static void main(String[] args) {String str = "How many $$ you have ? Do you have valid $$ amount?";String replacedString = str.replaceFirst("$$", "Dollars");System.out.println("replaceFirst() special chars output : " + replacedString);}}
Output:
replaceFirst() special chars output : How many $$ you have ? Do you have valid $$ amount?Dollars
This method does not work well with special characters.
So, You need to use the double backward slashes "\\$\\$" then it makes the right pattern.
String replacedString = str.replaceFirst("\\$\\$", "Dollars");
Now, recompile and run the program and observe the output.
Output:
Now it is on the right track.
replaceFirst() special chars output : How many Dollars you have ? Do you have valid $$ amount?
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceFirst(java.lang.String). Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.
5. replaceFirst() Internal Code
Internally, it calls the Pattern class methods. So, You can directly use the below code.
public String replaceFirst(String regex, String replacement) {return Pattern.compile(regex).matcher(this).replaceFirst(replacement);}
6. PatternSyntaxException with replaceFirst()
if the regular expression's syntax is invalid then it will throw runtime exception saying "PatternSyntaxException".
package com.javaprogramto.strings;public class StringReplaceFirstPatternSyntaxException {public static void main(String[] args) {String str = "Pattern invalid program";String replacedString = str.replaceFirst("[invalid}}", "invalid is not accecpted");System.out.println("replaceFirst() special chars output : " + replacedString);}}
Output:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 9[invalid}}^at java.base/java.util.regex.Pattern.error(Pattern.java:2027)at java.base/java.util.regex.Pattern.clazz(Pattern.java:2695)at java.base/java.util.regex.Pattern.sequence(Pattern.java:2138)at java.base/java.util.regex.Pattern.expr(Pattern.java:2068)at java.base/java.util.regex.Pattern.compile(Pattern.java:1782)at java.base/java.util.regex.Pattern.<init>(Pattern.java:1428)at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)at java.base/java.lang.String.replaceFirst(String.java:2081)at com.javaprogramto.strings.StringReplaceFirstPatternSyntaxException.main(StringReplaceFirstPatternSyntaxException.java:9)
7. Conclusion
In this article, you've seen how to replace the first match for a given pattern with a given value.
replaceFirst() is different than replace() and replaceAll() methods of string. You can find these from String series.
As usual, all programs are over GitHub.
GitHub
No comments:
Post a Comment
Please do not add any spam links in the comments section.