I have created a program which validates user input. One of the checks is for symbols, where the only symbol allowed is a decimal place if it is followed by at least one number. I used regular expressions for this, and as far as I have tested, they work correctly. It first checks for any symbols in the input and then checks if the format is any number of digits including none, followed by a decimal place, followed by at least one digit. However, I wrote the code below a few months ago, and now that I am trying to write about the program, I am struggling to find the exact explanation of the regular expressions, and this is where I require help.

regex1 = re.compile(r'(?![a-zA-Z0-9])[!-~]')
regex2 = re.compile(r'^\d*\.\d+?$')

if regex1.search(value):
   if regex2.search(value) == None:
      <value does not pass>

1 Answers

Mahmoud Elshahat On

Disclaimer: I am still learning regex, so forgive me, i will explain as far as my little understanding

first you will find everything you need in this python re and for practicing you should try how to

here is a quick explanation of some of the patterns

regex1 = re.compile(r'(?![a-zA-Z0-9])[!-~]') regex2 = re.compile(r'^\d*.\d+?$')

(?!...) Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.

[!-~] match single character i.e. any of !, -, ~

'^\d*\.\d+?$' has some symbols as ^ = search at the beginning of text, \d = digit 0-9, *,+ = multipliers, ? = non greedy search, \. = simple dot,