sarath
sarath

Reputation: 455

replace character from digit using replaceAll not working in java

item.setPrice(e.text().replaceAll("[^\\d\\.]", ""));

I want to replace all the character and special characters coming inside displaying Price value.....

But in one case Rs.1200.20 it is returning the value .1200.00

I want to avoid that . from the beginning. I want output like 1200.00 not .1200.00 How can i do that?

Upvotes: 0

Views: 98

Answers (2)

Sanjeev
Sanjeev

Reputation: 9946

You can use "[^\\d]+[.]" to replace that and also plain "Rs." to replace specifically.

Upvotes: 2

fge
fge

Reputation: 121712

Assuming all your prices are in the form xxxx.yyy where x and y are digits, you can use this code:

private static final Pattern PRICE_PATTERN
    = Pattern.compile("\\d+\\.\\d+");

// In code...
final Matcher m = PRICE_PATTERN.matcher(e.text());

item.setPrice(m.find() ? m.group() : "INVALID");

Doesn't handle all cases (for instance "1.2.3", "hello1.2world3.4", etc etc); it will only try and find the first valid price in the input string.

Upvotes: 0

Related Questions