简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM