String.matches (regex) returns false, although I think this should be true

I work with Java regular expressions.

Oh, I really miss Perl !! Java regular expressions are so complex.

Anyway below is my code.

oneLine = "{\"kind\":\"list\",\"items\""; System.out.println(oneLine.matches("kind")); 

I expected "true" to appear on the screen, but I could only see "false".

What is wrong with the code? And how can I fix this?

Thanks in advance!

+6
source share
3 answers

String#matches() takes a regex parameter as a parameter in which anchors are implicit. This way your regex pattern will be matched from beginning to end of line.

Since your line does not start with "kind" , it means it returns false .

Now, according to your current problem, I think there is no need to use regex . Just using String#contains() method will work fine: -

 oneLine.contains("kind"); 

Or, if you want to use matches , then create a regular expression to match the full string: -

 oneLine.matches(".*kind.*"); 
+8
source

The .matches method .matches designed to match the entire string. So you need something like:

 .*kind.* 

Demo: http://ideone.com/Gb5MQZ

+4
source

Matches try to match the entire string (implicit ^ and $ bindings), you want to use contains() to check for parts of the string.

+2
source

All Articles