0

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
Alan Moore
  • 71,299
  • 12
  • 93
  • 154
Sunil Kumar
  • 347
  • 1
  • 4
  • 18
  • 3
    You don't need `matches` here, use `contains`, unless you want to match a sequence of zeros that ends with 1. – Maroun Jun 20 '15 at 10:27
  • possible duplicate of [Difference between matches() and find() in Java Regex](http://stackoverflow.com/questions/4450045/difference-between-matches-and-find-in-java-regex) – Joe Jun 20 '15 at 10:35

2 Answers2

1

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.

JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226
1

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;
Guillaume Polet
  • 46,469
  • 4
  • 81
  • 115