我想要以下Java代码中的解决方案
字符串inputStr =“这是一个示例@ hostname1 @ host-name2,在这里我想将像:@test host- @ test1这样的字符串转换为格式,即美元,后跟大括号,字符串和右括号。
我需要的输出字符串
输出:“这是一个示例$ {hostname1} $ {host-name2},在这里我想将字符串::$ {test} host-$ {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} ");
这与regex匹配@(.*?)\\s
,后者捕获at符号和最近的空格之间的所有内容,并将其替换为所需的格式。
String 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.";
// 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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句