java 接受正整数的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6595413/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:32:45  来源:igfitidea点击:

regex which accept positive integer and nothing

javaregex

提问by hudi

hi I found on the Internet that this regexp accept positive number ^\d+$ and this accept nothing ^$ So no I wanna combine this two regexp but with no success. I try this (^\d+$)|(^$) but this didnt work. So help me with regexp which accept positive integer and nothing thx a lot

嗨,我在互联网上发现这个正则表达式接受正数 ^\d+$ 而这不接受任何 ^$ 所以不,我想将这两个正则表达式结合起来,但没有成功。我试试这个 (^\d+$)|(^$) 但这没有用。所以帮我使用正则表达式,它接受正整数,没有很多东西

回答by Bart Kiers

Simply do:

简单地做:

^\d*$

The *means: "zero or more times".

*意思是:“零次或多次”。

Since you've asked most questions with the Java tag, I'm assuming you're looking for a Java solution. Note that inside a string literal, the \needs to be escaped!

由于您已经使用 Java 标记询问了大多数问题,因此我假设您正在寻找 Java 解决方案。请注意,在字符串文字中,\需要转义!

A demo:

一个演示:

class Test {
  public static void main(String[] args) {
    String[] tests = {"-100", "", "2334", "0"};
    for(String t : tests) {
      System.out.println(t + " -> " + t.matches("\d*"));
    }
  }
}

produces:

产生:

-100 -> false
 -> true
2334 -> true
0 -> true

Note that matches(...)already validates the entire input string, so there's no need to "anchor" it with ^and $.

请注意,matches(...)已经验证了整个输入字符串,因此无需使用^和“锚定”它$

Beware that it would also return true for numbers that exceed Integer.MAX_VALUEand Long.MAX_VALUE. SO even if matches(...)returned true, parseInt(...)or parseLong(...)may throw an exception!

请注意,对于超过Integer.MAX_VALUE和 的数字,它也会返回 true Long.MAX_VALUE。SO即使matches(...)返回true,parseInt(...)parseLong(...)可能抛出异常!

回答by Marek Musielak

Try ^[0-9]*$. This one allows numbers and nothing.

试试^[0-9]*$。这个允许数字而没有。

回答by deStrangis

How about ^\d*$? That would accept a sequence of digits (i.e. a positive integer) by itself in a line without whitespace or an empty line.

怎么样^\d*$?这将在没有空格或空行的行中单独接受数字序列(即正整数)。