简单的正则表达式问题(答案很可能是特定于 Java 的):
"#This is a comment in a file".matches("^#")
这会返回错误。据我所知,^
表示它始终表示的意思,#
没有特殊含义,所以我将 ^#
翻译为“字符串开头的‘#’”。哪个应该匹配。在 Perl 中也是如此:
perl -e "print '#This is a comment'=~/^#/;"
打印“1”。所以我很确定答案是特定于 Java 的。有没有人能赐教一下?
谢谢。
最佳答案
Matcher.matches()
检查整个输入字符串是否与正则表达式匹配。
由于您的正则表达式仅匹配第一个字符,因此它返回 false
。
您需要使用 Matcher.find()
相反。
诚然,找到具体规范可能有点棘手,但它就在那里:
-
String.matches()
被定义为做与Pattern.matches(regex, str)
相同的事情。 -
Pattern.matches()
依次定义为Pattern.compile(regex).matcher(input).matches()
。-
Pattern.compile()
返回一个Pattern
。 -
Pattern.matcher()
返回一个Matcher
-
-
Matcher.matches()
记录如下(强调我的):Attempts to match the entire region against the pattern.
关于java - 为什么这个正则表达式在 Java 中不能像预期的那样工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4792024/