Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用正则表达式从字符串中提取数字_Java_Regex - Fatal编程技术网

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

Java 如何使用正则表达式从字符串中提取数字,java,regex,Java,Regex,我想从字符串s中提取12345里亚尔: 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.IllegalSt

我想从字符串
s
中提取
12345里亚尔

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类中的
find
matches
第一个方法遍历字符串并获得匹配

所以使用

...
if (matcher.find())
    System.out.println(matcher.group(1));
或者,如果您想确保整个字符串由正则表达式匹配

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

您想提取同一正则表达式中的数字和相邻单词吗?不,我只想提取数字