user1738224 user1738224 - 1 year ago 86
Java Question

how to extract a number from a String using regex

I want to extract

12345 Rial
from the String

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

but the following exception is being thrown

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

Can anyone point out why?

Answer Source

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

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

if (matcher.matches())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download