9

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

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

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'=~/^#/;"

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

Thank you.

3 Answers 3

17

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

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

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is the right answer, thank you. Is this documented somewhere? Because I cannot read this from the documentation of String.matches: "Tells whether or not this string matches the given regular expression." does not sound like what you described.
I've always understood "matches" to imply "the entire input", but I've added the full explanation (and how to find it) above.
2

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.

1 Comment

...which will only work if the string doesn't contain any newlines, unless you prepend (?s) to your regex...
0

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:

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

1 Comment

In this case, both anchors (^ and $) are unnecessary, as they are implied by matches().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.