3

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?

3 Answers 3

4

You do need to escape the backslashes in Java string literals:

"\\b\\d+\\b"

This of course only matches positive integers, not any integer as you said in your question. Was that your intention?

I've looked through other similar questions and I've tried using a double backslash but that doesn't work.

Then you must also have another error. I guess the problem is that you want to use Matcher.find instead of matches. 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 use Matcher.find:

Pattern pattern = Pattern.compile("\\b\\d+\\b");
Matcher matcher = pattern.matcher(quantityDesired);
if (matcher.find()) { ... }

Note

If you did actually want to match the entire string then you don't need the anchors:

if (quantityDesired.matches("\\d+")) {.......}

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Instead of a regex, you might look into Apache Commons Lang StringUtils.isNumeric

1 Comment

Note: This works only for positive numbers.
1

Why don't you prefer Integer.parseInt() method? It does what you want and it is more readable.

1 Comment

Watch out: parseInt fails for 9999999999999999999. Though the OP didn't specify if that is what he wants or not.

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.