且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查字符串是否仅包含Java中的数字

更新时间:2021-09-02 23:28:36

尝试

String regex = "[0-9]+";

String regex = "\\d+";

根据Java 正则表达式 + 表示一次或多次, \d 表示一位数。

As per Java regular expressions, the + means "one or more times" and \d means "a digit".

注意:双反斜杠是转义序列以获得单个反斜杠 - 因此,java字符串中的 \\d 为您提供实际结果: \d

Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d in a java String gives you the actual result: \d

参考文献:

Java正则表达式

Java字符转义序列

编辑由于在其他答案中有些困惑,我正在编写一个测试用例,并会详细解释更多的事情。

due to some confusion in other answers, I am writing a test case and will explain some more things in detail.

首先,如果您对此解决方案的正确性有疑问(或其他),请运行此测试c ase:

Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:

String regex = "\\d+";

// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));

// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));

问题1:是否需要添加 ^ $ 到正则表达式,所以它不匹配aa123bb?

Question 1: Isn't it necessary to add ^ and $ to the regex, so it won't match "aa123bb" ?

否。在java中,匹配方法(在问题中指定)匹配完整的字符串,而不是片段。换句话说,没有必要使用 ^ \\d + $ (即使它也是正确的)。请参阅上一个负面测试用例。

No. In java, the matches method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$ (even though it is also correct). Please see the last negative test case.

请注意,如果您使用在线正则表达式检查程序,那么这可能会有所不同。要在Java中匹配字符串的片段,您可以使用 find 方法,详细说明如下:

Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find method instead, described in detail here:

Java Regex中matches()和find()之间的区别

问题2:此正则表达式是否也与空字符串匹配,

否。正则表达式 \\\\ * 将匹配空字符串,但 \\d + 没有。星号 * 表示零或更多,而加号 + 表示一个或多个。请参阅第一个否定测试用例。

No. A regex \\d* would match the empty string, but \\d+ does not. The star * means zero or more, whereas the plus + means one or more. Please see the first negative test case.

问题3:编译正则表达式模式不是更快吗?

是。编译一次正则表达式模式确实更快,而不是每次调用匹配,因此,如果性能影响很重要,那么 Pattern 可以像这样编译和使用:

Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches, and so if performance implications are important then a Pattern can be compiled and used like this:

Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());