简体   繁体   中英

Regex: find numbers greater than specific value (with varying decimal lengths)

I am trying to regex find all values in a list that are greater than or equal to .03. The tricky part is that my values have between 9 and 15 decimal places.

My current code works somewhat but is unwieldy - any advice much appreciated:

^(?:0?\.[0-9][3-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|0?\.[0-9][3-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|0?\.[0-9][3-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])$

Thank you.

You can use an asterisk to denote zero or more of a digit:

^(?:0?\.\d[3-9]\d*)$

This has the added benefit of matching exactly 0.03 or something with (say) 100 decimal places.

If you want to be strict about the decimal places, you can use brace syntax, which matches any repetitions between 9 and 15 digits:

^(?:0?\.\d[3-9]\d{9,15})$

Note that, as written, this regex doesn't match anything greater than or equal to 0.03--it matches anything greater than or equal to 0.03 and less than 1, and it doesn't match, say, 0.1, which is greater than 0.03. To match anything greater than 0.03, best to skip regex entirely and parse the number.

You should simply parse your data as float :

From your pattern you seem to have the numbers already seperated very well - why use regex at all? You numbers fill the whole line or aren't matched at all ( r"^........$" so essentially you have:

t = """0.0000002
0.4
0.04
0.004
24544.23354
Also Bad"""

Simply split into lines and check each line as float

# splits the string into a list of lines
for line in (x.strip() for x in t.split("\n")):
    try:
        if float(line) >= 0.03:
            print(line)
        else: 
            print("Not ok:",line)
    except:
        print("Not ok:",line)

Output:

Not ok: 0.0000002
0.4
0.04
Not ok: 0.004
24544.23354
Not ok: Also Bad

Here you go: 0.030000000 - 0.999999999999999

Greater than or equal to .03 and less than 1.0
at 9-15 decimal places

0?\.(?:03\d{7,13}|0[4-9]\d{7,13}|[1-9]\d{8,14})

Expanded

 #  0.030000000  -  0.999999999999999
 0?
 \.
 (?:
      03 \d{7,13} 
   |  0 [4-9] \d{7,13} 
   |  [1-9] \d{8,14} 
 )

Note - this was machine generated, there could be some overlap.
Example: 0?\\.(?:0[3-9]\\d{7,13}|[1-9]\\d{8,14})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM