Java Regex String Replace replace(String line, String regexp, String replacement)

Here you can find the source of replace(String line, String regexp, String replacement)

Description

replace

License

Apache License

Parameter

Parameter Description
line The line of text where we want to apply the replacement
regexp The regular expression that indicates which are the parts of the line to be replaced
replacement The string that will replace the new content that will appear instead of the content matched by the regexp

Declaration


public static String replace(String line, String regexp, String replacement) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    /**/*from w  ww  .ja  va2 s  .c  o m*/
     * 
     * @param line
     *            The line of text where we want to apply the replacement
     * @param regexp
     *            The regular expression that indicates which are the parts of
     *            the line to be replaced
     * @param replacement
     *            The string that will replace the new content that will appear
     *            instead of the content matched by the regexp
     * @return
     */

    public static String replace(String line, String regexp, String replacement) {

        Pattern pattern = Pattern.compile(regexp);
        Matcher matcher = pattern.matcher(line);

        while (matcher.find()) {
            // System.out.println("------> " + matcher.group());
            line = line.replace(matcher.group(), replacement);
        }

        return line;
    }
}

Related

  1. replace(String content, String name, String value)
  2. replace(String input, Pattern pattern, Function replacementGenerator)
  3. replace(String input, Pattern regex, Function converter)
  4. replace(String inputStr, String patternStr, String replacementStr)
  5. replace(String inString, String oldPattern, String newPattern)
  6. replace(String message, ResourceBundle bundle)
  7. replace(String operateOn[], String from, String to)
  8. replace(String original, CharSequence target, CharSequence replacement)
  9. replace(String pattern, String replace, String s)