尝试
String regex = "[0-9]+";
或
String regex = "\\d+";
根据Java正则表达式,表示“一次或多次”,表示“一个数字”。+
\d
注意:“双反斜杠”是一个转义序列,用于获取单个反斜杠 - 因此,在java字符串中为您提供实际结果:\\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));
问题 1:
难道没有必要添加和正则表达式,因此它不会与“aa123bb”匹配吗?^
$
不。在java中,方法(在问题中指定)匹配的是完整的字符串,而不是片段。换句话说,没有必要使用(即使它也是正确的)。请参阅最后一个阴性测试用例。matches
^\\d+$
请注意,如果您使用在线“正则表达式检查器”,则其行为可能会有所不同。要在 Java 中匹配字符串片段,可以改用该方法,下面将对此进行详细描述:find
Java 正则表达式中的 matchs() 和 find() 之间的区别
问题 2:
这个正则表达式是否也与空字符串匹配?""
不。正则表达式将与空字符串匹配,但不匹配。星星表示零个或多个,而加号表示一个或多个。请参阅第一个阴性测试用例。\\d*
\\d+
*
+
问题 3
编译正则表达式模式不是更快吗?
是的。编译一次正则表达式模式确实更快,而不是每次调用 ,因此,如果性能影响很重要,则可以像这样编译和使用: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());