Reputation: 397
I am trying to match string using java regex, but my match is failing. What may be the issue in code below?
String line = "Copy of 001";
boolean b = Pattern.matches("001", line);
System.out.println("value is : "+b);
Output value is
value is : false
Upvotes: 0
Views: 159
Reputation: 691635
matches()
tests if the whole string matches the regex. It doesn't. Use Matcher.find()
instead. Or simply use String.contains()
, as you don't need a regex to match a literal sequence of characters.
Upvotes: 1
Reputation: 47608
matches
will match the whole string. Use a Matcher
and the find()
method instead:
boolean b = Pattern.compile("001").matcher(line).find();
Or make your pattern more flexible and allow it to have something prefixing the "001". For example:
".*001"
For something this simple, though, Pattern is an overkill and a simple indexOf
will do the job much more efficiently:
boolean b = line.indexOf("001") > -1;
Upvotes: 1