varatis
varatis

Reputation: 14740

Java - regex to match any integer

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?

Upvotes: 3

Views: 12222

Answers (3)

Mark Byers
Mark Byers

Reputation: 838106

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.

Upvotes: 4

DwB
DwB

Reputation: 38300

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

Upvotes: 2

Seyf
Seyf

Reputation: 889

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

Upvotes: 1

Related Questions