Here you can find the source of replaceFirstOccurrence(String originalText, String oldString, String newString)
Parameter | Description |
---|---|
originalText | to do replacement in |
oldString | string to be replaced |
newString | replacement text for oldString. |
public static String replaceFirstOccurrence(String originalText, String oldString, String newString)
//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); } }