This Example describes the way to Replace certain part of the whole String using regular expression. For this we are going to make program named Replaceall.java. The steps involved in program Replaceall.java are described below:-
Pattern p = 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 = p.matcher(text):- Creates a matcher for matching the given input against pattern p.
matcher.replaceAll("Java"):- This method will replace every occurrence of the input against the given pattern.
Output of the program:-
|Text before replacement is:kavaSun's regex library Kava is now kava
Text after replacement is:JavaSun's regex library Java is now Java
We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.
Posted on: August 30, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles