user1738224 user1738224 - 1 month ago 12
Java Question

how to extract a number from a String using regex

I want to extract

12345 Rial
from the String
s
:

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));


but the following exception is being thrown

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)


Can anyone point out why?

Answer

Pattern first needs to be found before you will be able to use it. You need to use either find or matches first methods from Matcher class to traverse string and get match.

So use

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

or if you want to make sure that entire string is matched by regex

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