我需要使用正则表达式将字符串替换为{}中的变量
例如:
"Hi, there are {online@US-server} players in the US server" to "Hi, there are 12 players in the US server"
在{}内的Strings变量内可以大于1
我需要此代码以允许用户修改消息。用户在{}之后的{}内添加变量,例如在示例“ US-server”中,因此用户没有列表来检查变量。变量可能尽可能奇怪,例如:'{online @ test-UK}''{online @ asdtest}'
public static String getReplaced(String d) {
String result = d.split("\\{online@")[0];
for (int i = 1; i < d.split("\\{online@").length; i++) {
String dd = d.split("\\{online@")[i];
Pattern p = Pattern.compile("(.*?)}(.*)");
Matcher m = p.matcher(dd);
if (m.lookingAt()) {
int count = 12;
result += count + m.group(2);
} else {
result += dd;
}
}
return result;
}
最佳答案
使用\\{online@(.+)\\}
作为正则表达式,使用匹配器获取第一个捕获组。这将为您提供@之后的部分。
正则表达式是指:\\{
:字母'{'online@
:字符串online@
.+
:至少一个字符(任何人)(.+)
:捕获组\\}
:乱码“}”
然后只需使用String#replaceAll(String regex, String replacement)
(doc here)。
例:
int myIntValue = 12;
String myString = "there are {online@US-server} players";
Pattern p = Pattern.compile("\\{online@(.+)\\}") ;
Matcher m = p.matcher(myString) ;
if (m.find()) { // true if the pattern is found anywhere in your string.
System.out.println("Variable part is : " + m.group(1)); // group 1 is the capturing group
System.out.println(myString.replaceAll("\\{online@.+\\}", String.valueOf(myIntValue)));
}
如果需要在单个字符串中找到多个占位符:
String myString = "there are {online@US-server} players ,and {online@whatever}";
Pattern p = Pattern.compile("\\{online@(.+)\\}") ;
Matcher m = p.matcher(myString) ;
while (m.find()) { // true if the pattern is found anywhere in your string.
System.out.println("Variable part is : " + m.group(1)); // group 1 is the capturing group
System.out.println(myString.replace("{online@"+m.group(1)+"}", String.valueOf(myIntValue)));
}
关于java - Java正则表达式与替换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60304593/