Merge two pattern into one

X.walt :

I need write a pattern to remove currency symbol and comma. eg Fr.-145,000.01 After the pattern matcher should return -145000.01.

The pattern i am using:

^[^0-9\\-]*([0-9\\-\\.\\,]*?)[^0-9\\-]*$

This will return -145,000.01

Then I remove the comma to get -145000.01, I want to ask if that's possible that I change the pattern and directly get -145000.01

String pattern = "^[^0-9\\-]*([0-9\\-\\.\\,]*?)[^0-9\\-]*$";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str);
if(m.matches()) {
 System.out.println(m.group(1));
}

I expect the output could resolve the comma

Marc G. Smith :

You can simply it with String.replaceAll() and simpler regex (providing you are expecting the input to be reasonably sane, i.e. without multiple decimal points embedded in the numbers or multiple negative signs)

   String str = "Fr.-145,000.01";
   str.replaceAll("[^\\d-.]\\.?", "")

If you are going down this route, I would sanity check it by parsing the output with BigDecimal or Double.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=122774&siteId=1