java - 如何使用正则表达式从字符串中提取数字

标签 java regex

我想从字符串s中提取12345 Rial:

String regx= ".* (\\d*) Rial";
String  s = "your balance is 12345 Rial your last"
Pattern pattern = Pattern.compile(regx);
Matcher matcher = pattern.matcher(s);
System.out.println(matcher.group(1));

但抛出以下异常

java.lang.IllegalStateException: No match found
 at java.util.regex.Matcher.group(Unknown Source)
 at ir.dena.avl.server.util.modbus.ChargeMessage.getBalanceFromIranCell(ChargeMessage.java:95)

谁能指出原因吗?

最佳答案

首先需要找到模式,然后才能使用它。您需要首先使用 Matcher 类中的 findmatches 方法来遍历字符串并获取匹配项。

所以使用

...
if (matcher.find())
    System.out.println(matcher.group(1));

或者如果您想确保整个字符串与正则表达式匹配

...
if (matcher.matches())
    System.out.println(matcher.group(1));

关于java - 如何使用正则表达式从字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24289304/

相关文章:

java - 如何在没有字符串或数组的情况下按升序对整数数字进行排序?

regex - 识别字符串中的地址编号

regex - 将句子大写的谷歌文档脚本

java - 获取匿名内部类的Class<?>对象

java - 从 AWS Java SDK 2.0 中的 GetObjectResponse 获取 S3Object

java - 在 json 数组中添加 json 对象,并在 sqlite 的 json 对象中添加 agian json 数组

java - GLSL ES语法错误: '(' parse error after main()

python 正则表达式去掉反斜杠

php - 我如何将 preg_match 与字母数字和 unicode 接受一起使用?

javascript - 带 markdown 的 unicode 正则表达式 [[WikiLinks]]