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

后端 未结 3 1055
别跟我提以往
别跟我提以往 2020-11-29 12:35

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

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

This returns false. As

3条回答
  •  隐瞒了意图╮
    2020-11-29 12:56

    The matches method matches your regex against the entire string.

    So try adding a .* to match rest of the string.

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

    which returns true. One can even drop all anchors(both start and end) from the regex and the match method will add it for us. So in the above case we could have also used "#.*" as the regex.

提交回复
热议问题