简单的正则表达式问题(答案很可能是 Java 特定的):
"#This is a comment in a file".matches("^#")
这会返回 false。据我所知,^
意味着它总是意味着什么#
没有什么特殊意义,所以我就翻译一下^#
作为“字符串开头的‘#’”。哪个应该匹配。在 Perl 中也是如此:
perl -e "print '#This is a comment'=~/^#/;"
打印“1”。所以我很确定答案是 Java 特有的。有人请赐教吗?
谢谢。
Matcher.matches() http://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#matches()检查是否整个输入字符串由正则表达式匹配。
由于您的正则表达式仅匹配第一个字符,因此它返回false
.
你会想要使用Matcher.find() http://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#find()反而。
诚然,找到具体的规范可能有点棘手,但它就在那里:
-
String.matches() http://download.oracle.com/javase/6/docs/api/java/lang/String.html#matches(java.lang.String)被定义为做同样的事情
Pattern.matches(regex, str)
.
-
Pattern.matches() http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#matches(java.lang.String,%20java.lang.CharSequence) in turn is defined as
Pattern.compile(regex).matcher(input).matches()
.
-
Pattern.compile() http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#compile(java.lang.String)返回一个
Pattern
.
-
Pattern.matcher() http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#matcher(java.lang.CharSequence)返回一个
Matcher
-
Matcher.matches() http://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#matches()记录如下(强调我的):
Attempts to match the entire region against the pattern.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)