English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
O método replaceFirst() da String Java substitui o primeiro subcadeia de caracteres correspondente ao padrão de expressão regular especificado.
Sintaxe do método replaceFirst()
string.replaceFirst(String regex, String replacement)
O método replaceFirst() tem dois parâmetros.
regex - Expressão regular a ser substituída (pode ser uma string típica)
replace - Substitua o primeiro subcadeia de caracteres correspondente por esta string
O método replaceFirst() retorna uma nova string, onde o primeiro item que coincide com a substring será substituído porSubstituiçãoCadeia de caracteres (replacement).
class Main { public static void main(String[] args) { String str1 = "aabbaaac"; String str2 = "Aprenda223Java55@"; //Expressão regular que representa uma sequência de números String regex = "\\d+"; //A primeira ocorrência de "aa" é substituída por "zz" System.out.println(str1.replaceFirst("aa", "zz")); // zzbbaaac //Substitua a primeira sequência de números por um espaço System.out.println(str2.replaceFirst(regex, " ")); // Aprenda Java55@ } }
No exemplo acima, "\\d+"is a regular expression that matches a sequence of digits."
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.
In regular expressions, some characters have special meanings. These meta-characters are:
\ ^ $ . | ? * + {} [] ()
If you need to match substrings that contain these meta-characters, you can use to escape these characters\.
//The first character of the + 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 the regular expression, please useJava String replaceAll() Method.