我有个问题,我已经忙了几天了,真的找不到答案.我相信这很简单,但我找不到.我搜遍了谷歌,没有找到任何能帮我做这件事的东西(也许我不知道该搜索什么?)
注意:在文本中占位符是{}中的任何内容。
所以我的问题是:
我有一根绳子:
“{前缀} {playerLeave}”
对于regex,我需要找到{前缀},用一个值替换它,然后检查新值(如果它有占位符等等)。
在这种情况下,情况会是这样的:
我尝试过的(并得到了最大的)是:
private static String translate(String text){
try{
while(text.matches("\\{(.*?)\\}")){
Matcher match = Pattern.compile("\\\b{(.*?)\\}\b").matcher(text);
while (match.find()) {
text = match(match.group(), text);
}
}
if (text.matches("\\{(.*?)\\}"))
translate(text);
return text;
}catch(Exception e) {
e.printStackTrace();
Bukkit.getConsoleSender().sendMessage(getMessage("&4ERROR: &cA placeholder failed!"));
return "";
}
}
private static String match(String match, String text){
text = text.contains("{Prefix}") ? text.replace(match, String.valueOf(Cach.Prefix))
text = text.contains("{TeleportDelay}") ? text.replace(match, String.valueOf(Cach.tpDelay)) : text.replace(match, "");
text = text.contains("{town}") ? text.replace(match, String.valueOf(Cach.StaticTown.getName())) : text.replace(match, "");
text = text.contains("{village}") ? text.replace(match, String.valueOf(Cach.StaticVillage.getName())) : text.replace(match, "");
text = text.contains("{kingdom}") ? text.replace(match, String.valueOf(Cach.StaticKingdom.getName())) : text.replace(match, "");
text = text.contains("{color}") ? text.replace(match, Cach.StaticKingdom.getColorSymbol()) : text.replace(match, "");
return text;
}问题是它在一定程度上起作用直到第二阶段。“征服你已经离开了{王国}”,如果我调试它,它是:
text.matches("{(.*?)}")在此代码块中为false:
if (text.matches("\\{(.*?)\\}"))
translate(text);提前感谢!
致以敬意,
托马斯
发布于 2017-02-05 23:06:37
这个regex Pattern.compile("\\\b{(.*?)\\}\b")中有一个错误:最后一个\b只有一个反斜杠。
再说一遍,你说:
我需要找到{前缀},用一个值替换它
但这一行中的组只匹配大括号内的文本(即前缀)。
所以你找到的所有匹配都包含没有大括号的组。
稍后由函数text.replace(match, ... )执行的match将只替换大括号中的文本。
如果我明白你的想法,我建议把这句话改为:
Pattern.compile("(\\{[^\\}]*\\})")https://stackoverflow.com/questions/42058280
复制相似问题