Why is this regex not working in Java?

trivial regex question (answer most likely depends on Java):

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

This returns false. As far as I see, ^ means that it always means, and # does not really matter, so I translated ^# as "A" at the beginning of the line. "Which should match. And so it goes, in Perl:

 perl -e "print '#This is a comment'=~/^#/;" 

prints "1". So I'm sure the answer is something specific to Java. Will someone please enlighten me?

Thanks.

+8
java regex
source share
3 answers

Matcher.matches() checks to see if the entire input string matches a regular expression.

Since your regular expression matches the very first character, it returns false .

Instead, you want to use Matcher.find() .

Of course, it can be a little difficult to find a specific specification, but it is there:

+17
source share

The matches method matches your regular expression for the entire string.

So try adding .* To match the rest of the line.

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

which returns true . You can even drop all anchors (both the beginning and the end) from the regular expression, and the match method will add it for us. So in the above case, we could use "#.*" As a regular expression.

+2
source share

This should meet your expectations:

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

Now the input line matches the pattern "The first char must be # , the rest must be any char"


Following Joachims comment, the following is equivalent:

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

All Articles