This Example describes the way to replace only the first subsequence of the String using regular expression. For this we are going to make program named Replace_First.java. The steps involved in program Replace_First.java are described below:-
Pattern pattern = Pattern.compile("(k|K)ava"):- Creating a pattern object and compiling the given regular expression into a pattern. Here 'k|K' means to replace all in place of character (k or K).
String text = "kavaSun's regex library Kava is now kava":-Declaring text in which character (K or k) is to be replaced by the matcher.
Matcher matcher = pattern.matcher(text):-Creates a matcher for matching the given input against pattern p.
matcher.replaceFirst("Java"):-This method will replace only the first occurrence of the input against the given pattern.
Output of the program:-
Text before replacing first subsequence is:-kavaSun's regex library Kava is now kava
Text after replacing first subsequence is:-JavaSun's regex library Kava is now kava
Rs. 20,000 US$ 300
Today: Rs. 10,000 US$150
Course Duration: 30 hrs
Posted on: August 29, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles