Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.matches(regex) returns false, although I think it should be true

Tags:

java

regex

match

I am working with Java regular expressions.

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

Anyway, below is my code.

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

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

What's wrong with the code? And how can I fix it?

Thank you in advance!!

like image 855
JSong Avatar asked Jan 30 '13 20:01

JSong


1 Answers

String#matches() takes a regex as parameter, in which anchors are implicit. So, your regex pattern will be matched at the beginning till the end of the string.

Since your string does not start with "kind", so it returns false.

Now, as per your current problem, I think you don't need to use regex here. Simply using String#contains() method will work fine: -

oneLine.contains("kind");

Or, if you want to use matches, then build the regex to match complete string: -

oneLine.matches(".*kind.*");
like image 88
Rohit Jain Avatar answered Sep 20 '22 01:09

Rohit Jain