Java Regex String Replace First replaceFirstOccurrence(String originalText, String oldString, String newString)

Here you can find the source of replaceFirstOccurrence(String originalText, String oldString, String newString)

Description

replace First Occurrence

License

MIT License

Parameter

Parameter Description
originalText to do replacement in
oldString string to be replaced
newString replacement text for oldString.

Return

originalTest with first occurrence of oldString replaced with newString.

Declaration

public static String replaceFirstOccurrence(String originalText, String oldString, String newString) 

Method Source Code

//package com.java2s;
/** Copyright by Barry G. Becker, 2000-2011. Licensed under MIT License: http://www.opensource.org/licenses/MIT  */

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

public class Main {
    /**/*  w w w . ja  va 2 s  .c o  m*/
     * @param originalText to do replacement in
     * @param oldString string to be replaced
     * @param newString replacement text for oldString.
     * @return originalTest with first occurrence of oldString replaced with newString.
     */
    public static String replaceFirstOccurrence(String originalText, String oldString, String newString) {
        // I just extracted the implementation of String.replaceFirst and put it here.
        // that may be considered cheating...
        Pattern pattern = Pattern.compile(oldString, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(originalText);

        StringBuffer sb = new StringBuffer();
        matcher.reset();
        if (matcher.find()) {
            matcher.appendReplacement(sb, newString);
        }
        matcher.appendTail(sb);
        return sb.toString();

        // this will work too, but you are not allowed to use this method.
        //return   originalText.replaceFirst(oldString, newString);
    }
}

Related

  1. replaceFirst(final String text, final String regex, final String replacement)
  2. replaceFirst(String content, String regex, String replacement)
  3. replaceFirst(String str, String regex, String replacement, int patternFlag)
  4. replaceFirst(StringBuffer buf, StringBuffer aux, Pattern pattern, String replacement, int pos)
  5. replaceFirstIgnoreCase(String source, String search, String replace)
  6. replaceFirstStatement(String source, String regex, String statement)
  7. replaceLeading(String string, char replaced, char replacedBy)