Reputation: 21
I am trying to add all the values to a string builder so i can serialize it. So, my stringbuilder looks like
sb = abc78.00xyz
Now, here i want to just remove the 0's after the decimal and want output like
Input -> Output I want
abc78.00xyz -> abc78xyz
abc78.08xyz -> abc78.08xyz
I tried using regex but it doesnt work Tried :
sb.toString().replaceAll("\\.0*$", "")
sb.toString().replaceAll("[.0]+", "")
but this only works if i have numbers.
Can someone tell me how i can get the desired values ?
Upvotes: 1
Views: 76
Reputation: 626754
You may use
s = s.replaceAll("(?<=\\d)\\.0+(?!\\d)", "");
See the regex demo
Details
(?<=\d)
- right before the current location, there must be a digit\.
- a dot0+
- one or more 0
digits(?!\d)
- not followed with any other digit.List<String> strs = Arrays.asList("abc78.00xyz", "abc78.08xyz");
for (String str : strs) {
System.out.println( str.replaceAll("(?<=\\d)\\.0+(?!\\d)", "") );
}
// => abc78xyz, abc78.08xyz
Upvotes: 1