动态替换串中的Java代码使用正则表达式
问题描述:
我在java代码要如下溶液动态替换串中的Java代码使用正则表达式
字符串inputStr =“这是一个样本@主机名1 @主机名2,我想将字符串转换等:@test宿主@ test1格式化,例如美元,然后是开放的花括号,字符串和大括号。
输出字符串我需要为
输出:“这是一个示例$ {主机名1} $ {主机名2}在这里我要像字符串转换:$ {测试}主机 - $ {TEST1}到格式,即美元,然后是开放的花括号,字符串和花括号。“;
下面我试着像
public void regEx(String intputStr){
String pattern = "\\S(@)\\S+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(commands);
String replacePattern = " \\$\\{\\S+\\} ";
int i=0;
while(m.find()) {
Pattern.compile(pattern).matcher(intputStr).replaceAll(replacePattern);
// System.out.println(m.group(i));
//i++;
}
// System.out.println(i);
System.out.println(intputStr);
}
,但我得到异常和无法继续。请帮忙。
答
你可以逃脱下面一行代码:
inputStr = inputStr.replaceAll("@(.*?)\\s", "\\${$1} ");
这正则表达式@(.*?)\\s
,这在符号和最近的空间捕捉之间的所有比赛,并与你想要的格式替换它。
String inputStr = "This is a sample @hostname1 @host-name2 where I want to convert the string like :@test [email protected] to format i.e dollar followed by open braces, string and close braces.";
// add space to match term should it occur as the last word
inputStr += " ";
inputStr = inputStr.replaceAll("@(.*?)\\s", "\\${$1} ");
inputStr = inputStr.substring(0, inputStr.length()-1);
System.out.println(inputStr);
输出:
This is a sample ${hostname1} ${host-name2} where I want to convert the string like :${test} host-${test1} to format i.e dollar followed by open braces, string and close braces.
这是如此briiliant。感谢您的解决方案。 –