Search code examples
javaregexguavaapache-commons

How to remove leading zeros from 'negative' alphanumeric string


Good day everyone.

I have an alphanumeric value. For example: "-00000050.43". And I need to convert it to BigDecimal (prefer, 'cuz it's an amount of $) or Float or Double (depends on the count of digits after '.'. Usually there are two digits) like "-50.43". So, I have 3 different solutions for positive alphanumeric value. Please see them below:

Regex

"00000050.43".replaceFirst("^0+(?!$)", "")

Apache Commons

StringUtils.stripStart("00000050.43","0");

And Google Guava

CharMatcher.is('0').trimLeadingFrom("00000050.43")

It doesn't work for a negative value. Unfortunately, I don't get any idea how to deal with '-' at the start. Thanks, guys! Have a good day.


Solution

  • You can use

    "00000050.43".replaceFirst("^(-?)0+(?!$)", "$1")
    

    The ^(-?)0+(?!$) pattern will match

    • ^ - start of string
    • (-?) - Group 1 ($1 in the replacement pattern will refer to this group value, if there is a - matched, it will be restored in the resulting string): an optional -
    • 0+ - one or more zeros
    • (?!$) - no end of string position immediately on the right allowed.

    See this regex demo.