tris
tris

Reputation: 49

How to check if the user input is in a specific format?

i am very new to coding, and am in need of some assistance, and would like to say sorry for such a novice question, but I could not word the question in a way to easily find help, which i am sure is out there. Anyways, to put it simply, I need to force the user when asked to input text, to have the format 'a=b'.

`message3 = raw_input("Enter a guess in the form a=b:")`

I would like to make it so that if the user does not enter the correct format, 'a=b', some error message will pop up telling them so.

Upvotes: 1

Views: 931

Answers (2)

simonzack
simonzack

Reputation: 20938

Here's how I would do it, expanding on my comment above. Since you're learning python, it's best if you learn python 3.

import sys
import re

s = input("Enter a guess in the form a=b:")
matched = re.match(r'(.+)=(.+)', s)
if matched is None:
   print('enter in the form of a=b')
   sys.exit(1)
a, b = matched.groups()
print(a, b)

In the regex, .+ matches a non-empty string. The brackets are a capturing group, so we can get a and b using .groups().

Upvotes: 1

Weafs.py
Weafs.py

Reputation: 22992

You can try this:

>>> import re
>>> string = raw_input("Enter a guess in the form a=b:")
Enter a guess in the form a=b: Delirious=    # Incorrect Format
>>> m = re.match(r'.+=.+', string)
>>> try:
        if m.group():
            print "Correct Format"
    except:
        print "The format isn't correct"
"The format isn't correct"
>>>
>>> string = raw_input("Enter a guess in the form a=b:")
Enter a guess in the form a=b: Me=Delirious    # Correct Format
>>> m = re.match(r'.+=.+', string)
>>> try:
        if m.group():
            print "Correct Format"
    except:
        print "The format isn't correct"
"Correct Format"

Upvotes: 1

Related Questions