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
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*"
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 Comment
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 Comments
a.0