1

I have a string "123.0" and use "123.0".matches( "(\\.)?0*$" ) to check if it has any trailing zeros but it does not match. The same regexp matches string correctly @ http://regexpal.com/

How about if I want to just replace the last zeros with something else. String.replace says:

replace(CharSequence target, CharSequence replacement) - Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

But "123.0".replace( "(\\.)?0*$", "" ) it will not replace the last ".0".

2 Answers 2

1

The java.lang.String.matches method matches the entire string, not part of it. (No need to specify ^ and $).

So your pattern string should be:

"\\d+\\.?0*"

Demo

UPDATE according to question edit:

You shoudl use replaceAll instead of replace. replace does not accept a regular expression. It interpret the first parameter literally.

"123.0".replaceAll("\\.0*$", "")
1
  • How about String.replace? Commented Jan 15, 2014 at 6:24
1

Unlike most other languages, java's matches requires the whole string to match, so you'll have to add a leading .* to your regex:

if (str.matches(".*\\.0+"))

Note that your regex seems a bit wrong - everything is optional, so it would match anything. Try this regex instead.

Also, because it had to match the whole string, ^ and $ are implied (code them if you want - it makes no difference)

4
  • 2
    This will even match a.0 Commented Jan 15, 2014 at 6:18
  • And how about String.replace. I've updated the questions with clarification. Commented Jan 15, 2014 at 6:25
  • @thefourtheye yes, just as OP's regex would. This regex is the closest to the intent if the code in the question (he's not validating the input, just testing if it ends in zeroes)
    – Bohemian
    Commented Jan 15, 2014 at 7:20
  • @markovuksanovic that's a totally different question. Better to ask a fresh question.
    – Bohemian
    Commented Jan 15, 2014 at 7:21

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.