您的位置:首页 > 编程语言 > Java开发

java Matcher匹配头尾截取替换字符串

2017-10-13 13:46 441 查看
在java 编程中,我们常常有这样的需求:需要将一段字符串内的特定字符串,按照一定规则查找出来或替换,比如匹配文本开头规则和结束规则。

以下就是Matcher的使用:

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

/**
* @Author changle
* @Time 17/10/12.
* @Desc 匹配头尾截取替换字符串
* 待替换内容:
* url: jdbc:mysql://${cot.identity.db.ip}:3306/${cot.identity.db.dbname}?useUnicode=true&characterEncoding=UTF8
* 替换后:
* url: jdbc:mysql://{{cot.identity.db.ip}}:3306/{{cot.identity.db.dbname}}?useUnicode=true&characterEncoding=UTF8
*/
public class CommonTest {
public static void main(String[] args) {
String str = "url: jdbc:mysql://${cot.identity.db.ip}:3306/${cot.identity.db.dbname}?useUnicode=true&characterEncoding=UTF8";
if (str.contains("${cot.")) {
Pattern leftpattern = Pattern.compile("\\$\\{");
Matcher leftmatcher = leftpattern.matcher(str);
Pattern rightpattern = Pattern.compile("}");
Matcher rightmatcher = rightpattern.matcher(str);
int begin = 0;
List<String> foundKeys = new ArrayList<>();
while (leftmatcher.find(begin)) {
rightmatcher.find(leftmatcher.start());
String configKey = str.substring(leftmatcher.start(), rightmatcher.end());
System.out.println(configKey.replace("${", "{{"));
foundKeys.add(configKey);
begin = rightmatcher.end();
}
System.out.println("原内容:"+str);
for (String foundkey : foundKeys){
str = str.replace(foundkey, foundkey.replace("${cot.","{{cot.").replace("}", "}}").replace("-","_"));
}
System.out.println("替换后:"+str);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息