Java – regular expressions match any integer

I have a problem that regular expressions match any int string

This is what I have:

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

But eclipse gave me:

Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )

I've looked at other similar problems. I try to use double backslashes, but it doesn't work Suggestions?

Solution

You need to escape the backslash in the Java string Text:

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

This of course matches only positive integers, not any integers you said in the question Is that your intention?

Then you must make another mistake I think the problem is that you have to use matcher Find, not match The former searches for patterns anywhere in the string, while the latter matches only when the entire string matches the pattern This is a how to use matcher Example of find:

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

be careful

If you really want to match the entire string, you don't need an anchor:

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

If you only want to accept integers suitable for Java int types, you should use integer ParseInt is used as seyf ü lislam stated, rather than parsing it yourself

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>