GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Java String.replaceFirst - Complete Tutorial with Examples Java String.replaceFirst MethodLast modified: April 20, 2025
The This method is useful when you need to modify only the first occurrence of a pattern in a string. It returns a new string with the replacement applied. The original string remains unchanged as strings are immutable in Java. Method SignatureThe method has two variants. The basic version takes a regex pattern and replacement string. The second version accepts regex flags for case-insensitive matching and other options.
Basic replaceFirst Example
This example demonstrates the simplest usage of ReplaceFirstBasic.java
package com.zetcode;
public class ReplaceFirstBasic {
public static void main(String[] args) {
String text = "The quick brown fox jumps over the lazy dog";
String result = text.replaceFirst("the", "a");
System.out.println("Original: " + text);
System.out.println("Modified: " + result);
}
}
In this example, we replace the first occurrence of "the" with "a". Note that the replacement is case-sensitive. The original string remains unchanged while a new modified string is returned. Case-Insensitive Replacement
This example shows how to perform case-insensitive replacement using regex
flags. We use ReplaceFirstCaseInsensitive.java
package com.zetcode;
import java.util.regex.Pattern;
public class ReplaceFirstCaseInsensitive {
public static void main(String[] args) {
String text = "The quick brown fox jumps over the lazy dog";
String result = text.replaceFirst("(?i)the", "a");
System.out.println("Original: " + text);
System.out.println("Modified: " + result);
}
}
We use the Replacing Digits
This example demonstrates replacing the first sequence of digits in a string.
We use the ReplaceFirstDigits.java
package com.zetcode;
public class ReplaceFirstDigits {
public static void main(String[] args) {
String text = "Order 12345 with price 67.89 USD";
String result = text.replaceFirst("\\d+", "XXXXX");
System.out.println("Original: " + text);
System.out.println("Modified: " + result);
}
}
The pattern Using Capturing Groups
This example shows how to use capturing groups in the replacement string. We can
reference matched groups using ReplaceFirstGroups.java
package com.zetcode;
public class ReplaceFirstGroups {
public static void main(String[] args) {
String text = "John Doe, age 30";
String result = text.replaceFirst("(\\w+) (\\w+), age (\\d+)",
"Last: $2, First: $1, Years: $3");
System.out.println("Original: " + text);
System.out.println("Modified: " + result);
}
}
The pattern captures three groups: first name, last name, and age. In the
replacement string, we rearrange these groups with descriptive labels. Replacing Special Characters
This example demonstrates replacing special regex characters. We need to escape
them properly or use ReplaceFirstSpecialChars.java
package com.zetcode;
import java.util.regex.Pattern;
public class ReplaceFirstSpecialChars {
public static void main(String[] args) {
String text = "Calculate 3 + 5 * 2";
// Using escaped characters
String result1 = text.replaceFirst("\\+", "plus");
System.out.println("Escaped: " + result1);
// Using Pattern.quote
String result2 = text.replaceFirst(Pattern.quote("*"), "times");
System.out.println("Quoted: " + result2);
}
}
The plus sign and asterisk are regex metacharacters. We either escape them with
backslashes or use Replacing with FunctionJava 9+ allows using a function to determine the replacement. This provides dynamic replacement based on the matched content. ReplaceFirstFunction.java
package com.zetcode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceFirstFunction {
public static void main(String[] args) {
String text = "Prices: $10, $20, $30";
Pattern pattern = Pattern.compile("\\$\\d+");
String result = pattern.matcher(text)
.replaceFirst(m -> "USD " + m.group().substring(1));
System.out.println("Original: " + text);
System.out.println("Modified: " + result);
}
}
We use a lambda function that receives the match and returns the replacement string. In this case, we transform "$10" into "USD 10". This approach provides flexible replacement logic based on the matched content. Replacing in Multiline Text
This example shows how to replace the first match in multiline text. We use the
ReplaceFirstMultiline.java
package com.zetcode;
import java.util.regex.Pattern;
public class ReplaceFirstMultiline {
public static void main(String[] args) {
String text = "First line\nSecond line\nThird line";
String result = text.replaceFirst("(?m)^.*$", "---");
System.out.println("Original:\n" + text);
System.out.println("Modified:\n" + result);
}
}
The SourceJava String.replaceFirst Documentation
In this article, we've explored various uses of the AuthorMy name is Jan Bodnar, and I am a dedicated programmer with many years of experience in the field. I began writing programming articles in 2007 and have since authored over 1,400 articles and eight e-books. With more than eight years of teaching experience, I am committed to sharing my knowledge and helping others master programming concepts. List all Java tutorials. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |