gpt4 book ai didi

Java:需要从字符串中提取数字

转载 作者:行者123 更新时间:2023-11-29 03:05:43 25 4
gpt4 key购买 nike

我有一个包含数字的字符串。类似于 “事件 #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);
}

Demo.

关于Java:需要从字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32290862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com