The String.replaceFirst() in Java replaces the first occurrence of a substring found that matches the given argument substring (or regular expression) with the specified replacement substring. The substring matching process starts from the beginning of the string (index 0) and ends after the first match is found, else to the end of string.
Note that we can not pass null as method arguments, but we can pass an empty string.
1. String.replaceFirst() API
The syntax of replaceFirst() is as follows. It searches for substring regex and replaces with replacement string. The regex can be normal string as well as a regular expression.
String replaceFirst(String regex, String replacement);
2. String.replaceFirst() Example
The following Java program replaces the first occurrence of “java” with an uppercase “JAVA” string.
String str = "howtodoinjava";
String newStr = str.replaceFirst("java", "JAVA");
System.out.println(newStr); //howtodoinJAVA
We can also use the regex as follows:
String string = "how to do in java";
String updatedString = string.replaceFirst("\\s", "-");
System.out.println(updatedString); //how-to do in java
3. Escaping Special Characters
Although we can pass the regex as substring pattern to match, the original string may contain special characters that we would not want to consider in pattern matching.
In regex, there are characters that have special meaning. These metacharacters are:
\ ^ $ . | ? * + {} [] ()
For such metacharacters, use double backward-slash (\\) to skip that meta character.
String string = "how+to+do+in+java";
String updatedString = string.replaceFirst("\\+", "-");
System.out.println(updatedString); //how-to+do+in+java
4. The ‘null’ is Not Allowed
A 'null'
is not allowed as either method argument. The method will throw NullPointerException if null is passed.
String updatedString = string.replaceFirst(null, "-");
Program output.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "this.pattern" is null
Happy Learning !!
Comments