在Java for String 类中有一个称为matches 的方法,如何使用此方法使用正则表达式检查我的字符串是否只有数字。我尝试了以下示例,但结果都返回 false。
String regex = "[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
String regex = "^[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
最佳答案
试试
String regex = "[0-9]+";
或
String regex = "\\d+";
根据 Java 正则表达式,+
表示“一次或多次”,\d
表示“一个数字”。
注意:“双反斜杠”是一个 转义序列,用于获得单个反斜杠 - 因此,java String 中的 \\d
会为您提供实际结果:\d
引用资料:
编辑:由于其他答案有些困惑,我正在编写一个测试用例,并将详细解释一些事情。
首先,如果您对此解决方案(或其他解决方案)的正确性有疑问,请运行此测试用例:
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));
问题一:
Isn't it necessary to add
^
and$
to the regex, so it won't match "aa123bb" ?
No. 在 java 中,matches
方法(在问题中指定)匹配完整的字符串,而不是片段。换句话说,没有必要使用 ^\\d+$
(即使它也是正确的)。请看最后一个负测试用例。
请注意,如果您使用在线“正则表达式检查器”,则其行为可能会有所不同。要在 Java 中匹配字符串的片段,您可以改用 find
方法,这里有详细描述:
Difference between matches() and find() in Java Regex
问题2:
Won't this regex also match the empty string,
""
?*
No. 正则表达式 \\d*
将匹配空字符串,但 \\d+
不匹配。星号 *
表示零或多个,而加号 +
表示一或多个。请看第一个负测试用例。
问题 3
Isn't it faster to compile a regex Pattern?
是的。编译一次正则表达式模式确实更快,而不是每次调用 matches
,因此如果性能影响很重要,那么 Pattern
可以这样编译和使用:
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());
关于java - 如何检查字符串是否仅包含Java中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15111420/