简体   繁体   English

为什么此正则表达式在Java中无法按预期工作?

[英]Why doesn't this regex work as expected in Java?

trivial regex question (the answer is most probably Java-specific): 琐碎的正则表达式问题(答案很可能是特定于Java的):

"#This is a comment in a file".matches("^#")

This returns false. 这将返回false。 As far as I can see, ^ means what it always means and # has no special meaning, so I'd translate ^# as "A '#' at the beginning of the string". 据我所知, ^表示其始终的含义,而#没有特殊含义,因此我将^#转换为“字符串开头的'#'”。 Which should match. 哪个应该匹配。 And so it does, in Perl: 在Perl中也是如此:

perl -e "print '#This is a comment'=~/^#/;"

prints "1". 打印“ 1”。 So I'm pretty sure the answer is something Java specific. 所以我很确定答案是特定于Java的。 Would somebody please enlighten me? 有人能启发我吗?

Thank you. 谢谢。

Matcher.matches() checks to see if the entire input string is matched by the regex. Matcher.matches()检查是否正则表达式匹配了整个输入字符串

Since your regex only matches the very first character, it returns false . 由于您的正则表达式仅匹配第一个字符,因此它返回false

You'll want to use Matcher.find() instead. 您将要改用Matcher.find()

Granted, it can be a bit tricky to find the concrete specification, but it's there: 当然,要找到具体的规范可能会有些棘手,但是它存在:

The matches method matches your regex against the entire string. matches方法将您的正则表达式与整个字符串匹配。

So try adding a .* to match rest of the string. 因此,请尝试添加.*以匹配其余字符串。

"#This is a comment in a file".matches("^#.*")

which returns true . 返回true One can even drop all anchors(both start and end) from the regex and the match method will add it for us. 甚至可以从正则表达式中删除所有锚(开始和结束), match方法将为我们添加它。 So in the above case we could have also used "#.*" as the regex. 因此,在上述情况下,我们也可以使用"#.*"作为正则表达式。

This should meet your expectations: 这应该符合您的期望:

"#This is a comment in a file".matches("^#.*$")

Now the input String matches the pattern "First char shall be # , the rest shall be any char" 现在输入的字符串匹配模式“第一个字符应为# ,其余字符应为任何字符”


Following Joachims comment, the following is equivalent: 在Joachims评论之后,以下内容是等效的:

"#This is a comment in a file".matches("#.*")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM