eclipse Java - 正则表达式匹配任何整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7641008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - regex to match any integer
提问by varatis
I'm having a problem having a regex that matches a String with any int.
我在使用与任何 int 匹配的字符串的正则表达式时遇到问题。
Here's what I have:
这是我所拥有的:
if(quantityDesired.matches("\b\d+\b")){.......}
But Eclipse gives me:
但是 Eclipse 给了我:
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?
我查看了其他类似的问题,并尝试使用双反斜杠,但这不起作用。建议?
回答by Mark Byers
You doneed to escape the backslashes in Java string literals:
您确实需要转义 Java 字符串文字中的反斜杠:
"\b\d+\b"
This of course only matches positiveintegers, not anyinteger 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 entirestring matches the pattern. Here's an example of how to use Matcher.find
:
那么你肯定还有另一个错误。我想问题是你想使用Matcher.find
而不是matches
. 前者在字符串中的任何位置搜索模式,而后者仅在整个字符串与模式匹配时才匹配。以下是如何使用的示例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.
如果您只想接受适合 Java int 类型的整数,您应该使用Seyfülislam 提到的Integer.parseInt ,而不是自己解析它。
回答by DwB
Instead of a regex, you might look into Apache Commons Lang StringUtils.isNumeric
您可以查看Apache Commons Lang StringUtils.isNumeric而不是正则表达式
回答by Seyfülislam ?zdemir
Why don't you prefer Integer.parseInt()method? It does what you want and it is more readable.
你为什么不喜欢Integer.parseInt()方法?它可以满足您的需求,并且更具可读性。