We are moved to new domain
Click -> www.ehowtonow.com
Thursday, 25 May 2017

How to replace all occurrences of a string

String java.util.regex.Matcher.replaceAll(String replacement)

Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.

This method first resets this matcher. It then scans the input sequence looking for matches of the pattern. Characters that are not part of any match are appended directly to the result string; each match is replaced in the result by the replacement string. The replacement string may contain references to captured subsequences as in the appendReplacement method.

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

Given the regular expression a*b, the input "aabfooaabfooabfoob", and the replacement string "-", an invocation of this method on a matcher for that expression would yield the string "-foo-foo-foo-".

Invoking this method changes this matcher's state. If the matcher is to be used in further matching operations then it should first be reset.

Parameters:
replacement The replacement string

Returns:

The string constructed by replacing each matching subsequence by the replacement string, substituting captured subsequences as needed

ReplaceAllOccurrence.java
package com.javatutorialcorner.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReplaceAllOccurrence {

 public static void main(String[] args) {
   Pattern pattern = Pattern.compile("Thirukural");
       String text = "Thirukural Thirukural Thirukral Thiruvalluvar Thiruvalluvar Thiruvalluvar";
       System.out.println("Source String : "+ text);
       Matcher matcher = pattern.matcher(text);
       String result = matcher.replaceAll("Thirukural in English");
       System.out.println("Result String after replace : "+result);

 }

}
Output
Source String : Thirukural Thirukural Thirukral Thiruvalluvar Thiruvalluvar Thiruvalluvar
Result String after replace : Thirukural in English Thirukural in English Thirukral Thiruvalluvar Thiruvalluvar Thiruvalluvar

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to replace all occurrences of a string Rating: 5 Reviewed By: eHowToNow