tdmsoares
tdmsoares

Reputation: 533

Regex not working in method replaceAll() - Android

I asked a question here: Regex: Differentiate boundary match ^ and Negation about a regex to be applied in method replaceAll(), to get a String with only digits and the minus sign (-) to allow negative numbers as well. I run the follow and it works fine in my java interpreter:

String onlyDigits = currencyStringValue.replaceAll("[\\D-]","").replaceAll("(?<!^)-","");

If I input: --25#54d51 -> Returns: -255451

25#54-d51 -> Returns: 255151

-25#54d51 -> Returns: -255451

dz-255451 -> Returns: -255451

But I'm trying the same thing in Android Studio, and only returns digits, debugging the app, I notice the onlyDigits get only numbers 0-9, ignoring the minus sign (-) in beginning...

What is it wrong and if there is a problem in code or solution, how can I solve this?

Thanks!

Upvotes: 1

Views: 674

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627083

The problem is with \D that matches any character but a digit. With the first replacement operation you remove all minuses together with other non-digits.

The solution is simple: turn \D into a negated character class [^\d] and add a hyphen into it so as to avoid removing minuses before the next replaceAll call.

Use

String onlyDigits = currencyStringValue.replaceAll("[^-\\d]","").replaceAll("(?<!^)-","");

See the IDEONE demo

Upvotes: 1

Related Questions