
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to count replace first occurrence of a string in Java
Problem Description
How to count replace first occurrence of a String?
Solution
Following example demonstrates how to replace first occurrence of a String in a String using replaceFirst() method of a Matcher class.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String args[]) { Pattern p = Pattern.compile("hello"); String instring = "hello hello hello."; System.out.println("initial String: "+ instring); Matcher m = p.matcher(instring); String tmp = m.replaceFirst("Java"); System.out.println("String after replacing 1st Match: " +tmp); } }
Result
The above code sample will produce the following result.
initial String: hello hello hello. String after replacing 1st Match: Java hello hello.
java_regular_exp.htm
Advertisements