Java 正则表达式中的空格 [英] Whitespace in Java's regular expression
问题描述
我正在尝试编写一个正则表达式来处理 IRC PRIVMSG 字符串.它是这样的:
I'm trying to write a regular expression to mach an IRC PRIVMSG string. It is something like:
:nick!name@some.host.com PRIVMSG #channel :message body
所以我写了以下代码:
Pattern pattern = Pattern.compile("^:.*\\sPRIVMSG\\s#.*\\s:");
Matcher matcher = pattern.matcher(msg);
if(matcher.matches()) {
System.out.println(msg);
}
它不起作用.我没有火柴.当我使用在线 javascript 测试器测试正则表达式时,我得到了匹配项.
It does not work. I got no matches. When I test the regular expression using online javascript testers, I got matches.
我试图找到原因,为什么它不起作用,但我发现空白符号有问题.以下模式会给我一些匹配:
I tried to find the reason, why it doesn't work and I found that there's something wrong with the whitespace symbol. The following pattern will give me some matches:
Pattern.compile("^:.*");
但是带有 \s 的模式不会:
But the pattern with \s will not:
Pattern.compile("^:.*\\s");
令人困惑.
推荐答案
java matches
方法再次来袭!如果 整个 字符串与输入匹配,则该方法仅返回 true.您没有在第二个冒号后包含捕获消息正文的任何内容,因此 整个 字符串不匹配.它适用于测试人员,因为如果输入的任何部分匹配,正常"正则表达式就是匹配".
The java matches
method strikes again! That method only returns true if the entire string matches the input. You didn't include anything that captures the message body after the second colon, so the entire string is not a match. It works in testers because 'normal' regex is a 'match' if any part of the input matches.
Pattern pattern = Pattern.compile("^:.*?\\sPRIVMSG\\s#.*?\\s:.*$");
应该匹配
这篇关于Java 正则表达式中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!