English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java String replaceFirst() method replaces the first substring that matches the regular expression in the string with the specified text.
The syntax of replaceFirst() method is:
string.replaceFirst(String regex, String replacement)
The replaceFirst() method has two parameters.
regex - The regular expression to be replaced (can be a typical string)
replace - Replace the first matching substring with this string
The replaceFirst() method returns a new string in which the first match of the substring will be replaced withReplacementString (replacement).
class Main { public static void main(String[] args) { String str1 = \ String str2 = \223Java55@"; //Regular expression representing a number sequence String regex = \+"; //The first occurrence of "aa" is replaced with "zz" System.out.println(str1.replaceFirst("aa", \ // zzbbaaac //Replace the first number sequence with a space System.out.println(str2.replaceFirst(regex, \ // Learn Java55@ } }
In the above example, \+" is a regular expression that matches a numeric sequence.
The replaceFirst() method can use a regular expression or a typical string as the first parameter. This is because a typical string itself is a regular expression.
Some characters have special meanings in regular expressions. These meta-characters are:
\ ^ $ . | ? * + {} [] ()
If you need to match substrings containing these meta-characters, you can use to escape these characters \.
//The first character of + Character class Main { public static void main(String[] args) { String str = "a+a-++b"; //Replace the first " +" System.out.println(str.replaceFirst("\\+", "#")); // a#a-++b } }
If you need to replace each substring that matches a regular expression, please useJava String replaceAll() Method.