trivial regex question (the answer is most probably Java-specific):
\"#This is a comment in a file\".matches(\"^#\")
This returns false. As
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("#.*")
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.
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:
Pattern.matches(regex, str)
.Pattern.compile(regex).matcher(input).matches()
.
Pattern
.Matcher
Attempts to match the entire region against the pattern.