我试图在输入中找到环境变量并用值替换它们.
env变量的模式是 ${\\.}
Pattern myPattern = Pattern.compile( "(${\\.})" );
String line ="${env1}sojods${env2}${env3}";
Run Code Online (Sandbox Code Playgroud)
我怎么能代替env1用1和env2用2和env3用3,所以在此之后我将有一个新的字符串1sojods23?
Bri*_*ach 44
Java中的字符串是不可变的,如果你在讨论需要查找和替换的任意数量的东西,这会使这有点棘手.
具体来说,你需要在定义你的替换Map,使用StringBuilder与StringBuffer和appendReplacements()方法的appendTail().最终结果将存储在您的Matcher.
Map<String, String> replacements = new HashMap<String, String>() {{
put("${env1}", "1");
put("${env2}", "2");
put("${env3}", "3");
}};
String line ="${env1}sojods${env2}${env3}";
String rx = "(\\$\\{[^}]+\\})";
StringBuilder sb = new StringBuilder(); //use StringBuffer before Java 9
Pattern p = Pattern.compile(rx);
Matcher m = p.matcher(line);
while (m.find())
{
// Avoids throwing a NullPointerException in the case that you
// Don't have a replacement defined in the map for the match
String repString = replacements.get(m.group(1));
if (repString != null)
m.appendReplacement(sb, repString);
}
m.appendTail(sb);
System.out.println(sb.toString());
Run Code Online (Sandbox Code Playgroud)
输出:
1sojods23
Run Code Online (Sandbox Code Playgroud)
我知道这已经老了,我自己在寻找一个appendReplacement/appendTail例子,当我找到它时; 然而,OP的问题并不需要我在这里看到的那些复杂的多线解决方案.
在这种情况下,当要替换的字符串保持自己要替换的值时,可以通过以下方式轻松完成replaceAll:
String line ="${env1}sojods${env2}${env3}";
System.out.println( line.replaceAll("\\$\\{env([0-9]+)\\}", "$1") );
// Output => 1sojods23
Run Code Online (Sandbox Code Playgroud)
当根据每个匹配的某些条件或逻辑替换是随机的时,您可以使用appendReplacement/appendTail例如
希望您会发现此代码有用:
Pattern phone = Pattern.compile("\\$\\{env([0-9]+)\\}");
String line ="${env1}sojods${env2}${env3}";
Matcher action = phone.matcher(line);
StringBuffer sb = new StringBuffer(line.length());
while (action.find()) {
String text = action.group(1);
action.appendReplacement(sb, Matcher.quoteReplacement(text));
}
action.appendTail(sb);
System.out.println(sb.toString());
Run Code Online (Sandbox Code Playgroud)
输出是预期的:1sojods23。
这给你1sojods23:
String s = "${env1}sojods${env2}${env3}";
final Pattern myPattern = Pattern.compile("\\$\\{[^\\}]*\\}");
Matcher m = myPattern.matcher(s);
int i = 0;
while (m.find()) {
s = m.replaceFirst(String.valueOf(++i));
m = myPattern.matcher(s);
}
System.out.println(s);
Run Code Online (Sandbox Code Playgroud)
这也有效:
final String re = "\\$\\{[^\\}]*\\}";
String s = "${env1}sojods${env2}${env3}";
int i = 0;
String t;
while (true) {
t = s.replaceFirst(re, String.valueOf(++i));
if (s.equals(t)) {
break;
} else {
s = t;
}
}
System.out.println(s);
Run Code Online (Sandbox Code Playgroud)
are*_*tai -2
匹配后使用组${env1}将是您的第一个组,然后使用正则表达式替换每个组中的内容。
Pattern p = Pattern.compile("(${\\.})");
Matcher m = p.matcher(line);
while (m.find())
for (int j = 0; j <= m.groupCount(); j++)
//here you do replacement - check on the net how to do it;)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35298 次 |
| 最近记录: |