1

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!

7
  • 1
    replaceAll("[\\D]","") removes any non-digit character including -. What are you trying to do here? Commented Mar 22, 2016 at 23:19
  • Try String onlyDigits = currencyStringValue.replaceAll("[^-\\d]","").replaceAll("(?<!^)-","");. Commented Mar 22, 2016 at 23:20
  • 1
    @Pshemo what a silly mistake I did... Commented Mar 22, 2016 at 23:21
  • @Pshemo I changed to replaceAll("[\\D-]","").replaceAll("(?<!^)-","") and the problem kept. But I corrected my code with the suggestion from the answer below and now It works fine Commented Mar 22, 2016 at 23:33
  • Isn't that same solution which you already get here: stackoverflow.com/a/36144843/1393766? Commented Mar 22, 2016 at 23:34

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Before it was my mistake, but I corrected and the problem happened again. But now thanks to you it works fine!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.