[英]Unable to get Matcher.replaceAll to work properly
I am having some weird issues with a pattern replace. 我有一些模式替换的奇怪问题。
I have these two patterns: 我有这两种模式:
private static final Pattern CODE_ANY = Pattern.compile("&[0-9a-fk-or]");
private static final Pattern CODE_BLACK = Pattern.compile(ChatColour.BLACK.toString());
ChatColour.BLACK.toString() returns "&0" ChatColour.BLACK.toString()返回“&0”
Next, I have this code: 接下来,我有这个代码:
public static String Strip(String message)
{
while (true)
{
Matcher matcher = CODE_ANY.matcher(message);
if (!matcher.matches())
break;
message = matcher.replaceAll("");
}
return message;
}
I have tried a couple different approaches, but nothing gets replaced. 我尝试了几种不同的方法,但没有任何东西被取代。 The initial version just called each CODE_xxx pattern one after the other, but users were bypassing that by doubling up on ampersands. 初始版本一个接一个地调用每个CODE_xxx模式,但是用户通过将&符号加倍来绕过它。
I just do not understand why this isn't removing anything.. I know it is definitely getting called, as I have printed debug messages to the console to check that. 我只是不明白为什么这没有删除任何东西..我知道它肯定被调用,因为我已经打印调试消息到控制台检查。
// Morten //莫滕
matches()
checks if the complete input string matches the pattern, whereas find()
checks if the pattern can be found somewhere in the input string. matches()
检查完整的输入字符串是否与模式匹配 ,而find()
检查是否可以在输入字符串的某处找到模式。 Therefor, I would rewrite your method as: 因此,我会将您的方法重写为:
public static String strip(String message) // lowercase strip due to Java naming conventions
{
Matcher matcher = CODE_ANY.matcher(message);
if (matcher.find())
message = matcher.replaceAll("");
return message;
}
Just realized, this can be done with a one liner: 刚刚意识到,这可以通过一个班轮完成:
public static String strip(String message) {
return message.replaceAll("&[0-9a-fk-or]", "");
}
Using the replaceAll()
method you don't need a precompiled pattern, but you could extract the regex to a final field of type String. 使用replaceAll()
方法不需要预编译模式,但可以将正则表达式提取到String类型的final字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.