我有一个包含数字的字符串。类似于 “事件 #492 - 标题描述”
。
我需要从这个字符串中提取数字。
尝试过
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(theString);
String substring =m.group();
通过获取错误
java.lang.IllegalStateException: No match found
我做错了什么?
正确的表达方式是什么?
对于这么简单的问题,我很抱歉,但我搜索了很多,仍然没有找到如何做到这一点(也许是因为这里太晚了......)
最佳答案
您遇到此异常是因为您需要在访问 group
之前调用匹配器上的 find()
:
Matcher m = p.matcher(theString);
while (m.find()) {
String substring =m.group();
System.out.println(substring);
}
关于Java:需要从字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32290862/