Search code examples
pythonpython-re

Check Python String Formatting


I can accept user's input in two formats:

  1. 123
  2. 123,234,6028

I need to write a function/a few lines of code that check whether the input follows the correct format.

The rules:

  1. If a single number input, then it should be just a number between 1 and 5 digits long
  2. If more then one number, then it should be comma-separated values, but without spaces and letters and no comma/period/letter allowed after the last number.

The function just checks if formatting correct, else it prints Incorrect formatting, try entering again.

I would assume I would need to use re module.

Thanks in advance


Solution

  • You can use a simple regex:

    import re
    
    validate = re.compile('\d{1,5}(?:,\d{1,5})*')
    
    validate.fullmatch('123') # valid
    
    validate.fullmatch('123,456,789') # valid
    
    validate.fullmatch('1234567') # invalid
    

    Use in a test:

    if validate.fullmatch(your_string):
        # do stuff
    else:
        print('Incorrect formatting, try entering again')