我尝试创建一种方法,通过 IRC 消息将禁止的单词添加到我的 IRC 审核机器人中。 添加语法如下:
!addword #channel+regex+5+enabled
其中“regex”是正则表达式,用于检查发送的消息中是否有禁止的单词。
我的问题是单词边界 '\b' 不起作用。所以,如果我尝试这样做
!addword #channel+\bban\b+5+enabled
仅当发送的消息内容等于“ban”时,机器人才会禁止“ban”一词。例如,“请禁止我”这句话不会被禁止。使用双反斜杠根本不起作用。
其他正则表达式(如 [abc]、. 等)也可以工作,所以我必须假设这与字符“\”有关。
处理它的代码如下:
添加禁用词:
word = s.substring(nthOccurrence(s, '+', 1) + 1,
nthOccurrence(s, '+', 2));
其中“s”是添加禁用词的消息
模式匹配:
Pattern p=Pattern.compile(word.toLowerCase());
Matcher m=p.matcher(sentMessage.toLowerCase());
if(m.matches()) sendBAN(targetChannel, sender);
答案可能是显而易见的,但我就是无法弄清楚。感谢任何能解决这个问题的人。
最佳答案
我认为你必须转义java中的单词边界,这样它就会变成 \\bban\\b
并使用 find()
而不是 matches( )
示例:
public static void main(String[] args) {
String[] test = {"ban me please","ban","This should not be banned","hello"};
Pattern p = Pattern.compile("\\bban\\b");
for(String s: test) {
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println("Banning: " + s);
} else {
System.out.println("Not Banning: " + s);
}
}
}
提供以下内容:
Banning: ban me please
Banning: ban
Not Banning: This should not be banned
Not Banning: hello
关于java - 当包含反斜杠时,从用户输入创建正则表达式模式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28811768/