Home > Software engineering >  How make a regex to check if a string is a float number with 7 digits and any value decimal place?
How make a regex to check if a string is a float number with 7 digits and any value decimal place?

Time:12-10

How make a regex to check if a string is a float number with 7 digits and any value decimal place?

Being acceptable as decimal separator ; : - , . ?

So I need:

import re

    rgx = re.compile('What is the regex sintaxe for it ?')

tests=[7000000.00 7000000:00 7000000,00 7000000-00 7AAAAAA.00 700000000.00 70.00]

for s in tests:
    m = rgx.search(s)
    print(bool(m), s)

True 7000000.00
True 7000000:00
True 7000000,00
True 7000000-00
False 7AAAAAA.00
False 700000000.00
False 70.00

]

Example of how use regex

import re
    
    rgx = re.compile(r'\d (?:,\d*)?')
    
    tests=['7000000.00', '7000000:00', '7000000,00', '7000000-00', '7AAAAAA.00', '700000000.00', '70.00']
    
    for s in tests:
        m = rgx.search(s)
        print(bool(m), s)

CodePudding user response:

Check for 7 digits, followed by one non whitespace, non digit and non alphanumeric character and ends with unlimited numbers:

import re

rgx = re.compile(r'[0-9]{7}[\S\D\W]{1}[0-9] $')
# [0-9]{7}      >> Seven digits
# [\S\D\W]{1}   >> One non whitespace, non digit and non alphanumeric character
# [0-9].$       >> Ends with unlimited numbers

tests = "7000000.00 7000000:00 7000000,00 7000000-00 7AAAAAA.00 700000000.00 70.00"

for t in tests.split(" "):
    print(True if rgx.match(t) else False, t)

Out:

(True, '7000000.00')
(True, '7000000:00')
(True, '7000000,00')
(True, '7000000-00')
(False, '7AAAAAA.00')
(False, '700000000.00')
(False, '70.00')

CodePudding user response:

After you specify a character class, you can specify how many of that character is needed using curly braces i.e. {1,2} meaning between 1 and 2 characters or {4} meaning 4 characters

re.compile(r'(^|\D)\d{7}[-.;:,]\d ')

Here's a rundown of the regex:

(^|\D) Means that either the character must not be a number, or must be the start of a line
\d{7} Seven digits in a row
[-.;:,] Any of your characters denoting a decimal point
\d One or more digits

Of course you can add ^ and $ to ensure that the number is the only thing in the string if that's useful.

  • Related