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
2
  • 3
    You don't need matches here, use contains, unless you want to match a sequence of zeros that ends with 1. Commented Jun 20, 2015 at 10:27
  • possible duplicate of Difference between matches() and find() in Java Regex Commented Jun 20, 2015 at 10:35

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Thank you got it,, i would have used "*.001"
No, that would be an invalid regex. .*001 would work. But don't use regexes where simple contains() call work fine (and are simpler and more efficient).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.