I’m having a problem having a regex that matches a String with any int.
Here’s what I have:
if(quantityDesired.matches("\b\d+\b")){.......}
But Eclipse gives me:
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
I’ve looked through other similar questions and I’ve tried using a double backslash but that doesn’t work. Suggestions?
You do need to escape the backslashes in Java string literals:
This of course only matches positive integers, not any integer as you said in your question. Was that your intention?
Then you must also have another error. I guess the problem is that you want to use
Matcher.findinstead ofmatches. The former searches for the pattern anywhere in the string, whereas the latter only matches if the entire string matches the pattern. Here’s an example of how to useMatcher.find:Note
If you did actually want to match the entire string then you don’t need the anchors:
And if you only want to accept integers that fit into a Java int type, you should use Integer.parseInt as Seyfülislam mentioned, rather than parsing it yourself.