Reputation: 360
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!!
Upvotes: 6
Views: 1993
Reputation: 213401
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.*");
Upvotes: 8
Reputation: 56779
The .matches
method is intended to match the entire string. So you need something like:
.*kind.*
Demo: http://ideone.com/Gb5MQZ
Upvotes: 4
Reputation: 23373
Matches tries to match the whole string (implicit ^
and $
anchors), you want to use contains()
to check for parts of the string.
Upvotes: 2