Java正则表达式替换占位符

项目中使用一个功能,替换字符串中的占位符,当占位符的名称相近时,如:@id 和 @id1;不能完全区分替换;

测试代码如下:

测试1:String JAVARGGEX = "@[a-zA-Z0-9-_$#]*";
    	String text="@id=1 and @idx=3";
        Pattern pattern = Pattern.compile(JAVARGGEX);
		Matcher matcher = pattern.matcher(text);
		while (matcher.find()) {
			String name = matcher.group();
			System.out.println(name);
			if(name.equals("@id")){
				//text=matcher.replaceAll("222");
				text=text.replaceAll(name, "11"); 字符串替换
				
			}			
		}
		System.out.println(text); 
输出
@id
@idx
11=1 and 11x=3
 
 
测试2:String JAVARGGEX = "@[a-zA-Z0-9-_$#]*";
    	String text="@id=1 and @idx=3";
        Pattern pattern = Pattern.compile(JAVARGGEX);
		Matcher matcher = pattern.matcher(text);
		while (matcher.find()) {
			String name = matcher.group();
			System.out.println(name);
			if(name.equals("@id")){
				text=matcher.replaceAll("222");//matcher替换
				
				
			}			
		}
		System.out.println(text); 

 
 
public static String patternReplace(String text, String key, String value,String reg) {
		
		if( Xutil.isNullOrEmpty(reg)){
			String JAVARGGEX = "@[a-zA-Z0-9-_$#]*";
			reg=JAVARGGEX;
		}
		
		StringBuffer sb = new StringBuffer();
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(text);
		while (matcher.find()) {
			String name = matcher.group();
			System.out.println(name);
			if (name.equals(key)) {
				matcher.appendReplacement(sb, value);

			}
		}
		matcher.appendTail(sb);
		System.out.println(sb.toString());
		return sb.toString();

	}
测试使用:matcher.appendReplacement(sb, value);可以达到效果。
以上仅仅自我尝试,如有错误,请指正,相互学习!


猜你喜欢

转载自blog.csdn.net/b850824/article/details/79220389