尝试
String regex = "[0-9]+";
要么
String regex = "\d+";
按照Java 正则表达式 ,其
+含义是“一次或多次”,并且其
d含义是“数字”。
注意:“双反斜杠”是一个 转义序列, 用于获取单个反斜杠-因此,
\d在Java字符串中会提供实际结果:
d
参考文献:
Java正则表达式
Java字符转义序列
编辑: 由于其他答案有些混乱,我正在编写一个测试用例,并将详细解释一些其他内容。
首先,如果您对该解决方案(或其他解决方案)的正确性有疑问,请运行以下测试案例:
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:
不一定要在regex中添加
^和$,所以它不匹配“ aa123bb”吗?
否。
在Java中,
matches方法(在问题中指定)匹配完整的字符串,而不是片段。换句话说,没有必要使用
^\d+$(即使它也是正确的)。请查看最后一个否定测试用例。
请注意,如果您使用在线“正则表达式检查器”,则其行为可能有所不同。要匹配Java中字符串的片段,您可以改用
find方法,在此进行详细说明:
Java
Regex中match()和find()之间的区别
问题2:
这个正则表达式也不会匹配空字符串
""吗?*
否 。正则表达式
\d*将匹配空字符串,但
\d+不匹配。星号
*表示零或多个,而加号
+表示一个或多个。请参阅第一个否定测试用例。
问题3
编译正则表达式模式不是更快吗?
是。
确实,一次编译正则表达式模式比在每次调用regex模式时都要快
matches,因此,如果性能影响很重要,则
Pattern可以像这样编译和使用a :
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());


