pythonregex-group

How do I write responsive regular expression in Python?


I want to get up to the first digit other than 0 after the dot. If there is a number other than 0 after the dot, it should be taken as 2 digits. So it must be sensitive.How do I do this with regular expressions or Python math library? Here are examples

"0.00820289933" => "0.008"
"0.00000025252" => "0.0000002"
"0.858282815215" => "0.85"
"0.075787842545" => "0.07"
"1.100000010999" => "1.10"
"0.0"            => "0.0"
"0.000000000000" => "0.0" 
"0.000365266565" => "0.0003" 
"0.000036526656" => "0.00003" 
"0.000003652665" => "0.000003" 
"0.000000365266" => "0.0000003" 

I tried this

def format_adjusted_value(value):
    str_value = str(value)

    if '.' in str_value:
        match = re.match(r'(\d*\.\d*?[1-9])0*$', str_value)

        if match:
            formatted_value = match.group(1)
        else:
            match = re.match(r'(\d*\.\d*?[0-9])0*$', str_value)
            formatted_value = match.group(1) if match else str_value
    else:
        formatted_value = str_value

    return formatted_value

Solution

  • What about using a simple \d*\.(?:[^0]|0+)[^0]:

    import re
    
    def format_adjusted_value(value):
        m = re.search(r'\d*\.(?:[^0]|0+)[^0]', str(value))
        if m:
            return m.group(0)
        return value
    

    NB. [^0] could be [1-9] if you have characters other than digits.

    Output:

    0.00820289933: 0.008
    0.00000025252: 0.0000002
    0.858282815215: 0.85
    0.075787842545: 0.07
    

    Regex demo

    \d*\.       # match digits (optional) and a .
    (?:[^0]|0+) # match a non zero or one or more zeros
    [^0]        # match a non-zero
    

    Alternative regex: \d*\.(?:0+[1-9]|\d{,2})

    0.00820289933: 0.008
    0.00000025252: 0.0000002
    0.858282815215: 0.85
    0.075787842545: 0.07
    0.: 0.
    0.0: 0.0
    0.000000: 0.00
    

    Regex demo