| Refresh | Home EGTry.com

match a pattern in multiplace locations and get replaced through a callback function


Input

ohn.smith@gmail.com
user.name@domain.com@@@

Output

jOHN.sMITH@gMAIL.cOM
uSER.nAME@dOMAIN.cOM@@@

match and replace code

package egtry.regex;

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

public class MatchReplace {

	
	public static void main(String[] args) {
		String text="john.smith@gmail.com\nuser.name@domain.com@@@";
		
		Pattern pat=Pattern.compile("(\\w+)");
		
		StringBuffer buff=new StringBuffer();
		
		int offset=0;
		
		Matcher m=pat.matcher(text);
		
		while(!m.hitEnd()) {
			if (m.find(offset)) {
				int fromIndex=m.start();
				int endIndex=m.end();
				buff.append(text.substring(offset,fromIndex));
				buff.append(replace(m.group(1)));
				offset=m.end();
			}

		}
		System.out.println(buff.toString()+text.substring(offset));
	}
	
	public static String replace(String origin) {
		return origin.charAt(0)+origin.substring(1).toUpperCase();
	}
	


}