为什么这个正则表达式在Java中没有像预期的那样工作? [英] Why doesn't this regex work as expected in Java?

查看:138
本文介绍了为什么这个正则表达式在Java中没有像预期的那样工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

琐碎的正则表达式问题(答案很可能是特定于Java的):

trivial regex question (the answer is most probably Java-specific):

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

返回false。据我所知, ^ 表示它总是意味着什么,没有特殊含义,所以我想将 ^#翻译为字符串开头的A'#'。哪个应该匹配。它确实如此,在Perl中:

This returns 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 -e "print '#This is a comment'=~/^#/;"

打印1。所以我很确定答案是Java特有的。有人请赐教我吗?

prints "1". So I'm pretty sure the answer is something Java specific. Would somebody please enlighten me?

谢谢。

推荐答案

< a href =http://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#matches() =noreferrer> Matcher。 matches() 检查整个输入字符串是否与正则表达式匹配。

Matcher.matches() checks to see if the entire input string is matched by the regex.

由于你的正则表达式只匹配第一个字符,它返回 false

Since your regex only matches the very first character, it returns false.

你想要使用 Matcher.find () 而不是。

You'll want to use Matcher.find() instead.

当然,找到具体的规范可能有点棘手,但它就在那里:

Granted, it can be a bit tricky to find the concrete specification, but it's there:


  • String.matches() 被定义为与<$ c $做同样的事情c> Pattern.matches(regex,str)。
  • Pattern.matches() 依次被定义为 Pattern.compile (正则表达式).matcher(输入).matches()

    • String.matches() is defined as doing the same thing as Pattern.matches(regex, str).
    • Pattern.matches() in turn is defined as Pattern.compile(regex).matcher(input).matches().
      • Pattern.compile() returns a Pattern.
      • Pattern.matcher() returns a Matcher

      尝试将整个区域与模式匹配。


    • 这篇关于为什么这个正则表达式在Java中没有像预期的那样工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆