Reputation: 621
I am making a program that has a small way of self learning, but now I want to get "information" from the output like:
>>>#ff0000 is the hexcode for the color red
I want to filter with reggular expressions
that the user filled this sentence is the hexcode for the color
, and that I retrieve the name of the color and the hexcode. I have put a small code below how I want to works:
#main.py
strInput = raw_input("Please give a fact:")
if "{0} is the hexcode for the color {1}" in strInput:
# {0} is the name of the color
# {1} is the hexcode of the color
print "You give me an color"
if "{0} is an vehicle" in strInput:
# {0} is an vehicle
print "You give me an vehicle"
Is this possible with reggular expressions
, and what is the best way to do it with reggular expressions
?
Upvotes: 0
Views: 34
Reputation: 5019
You can read about regular expressions in Python in the standard library documentation. Here, I'm using named groups to store the matched value into a dictionary structure with a key that you choose.
>>> import re
>>> s = '#ff0000 is the hexcode for the color red'
>>> m = re.match(r'(?P<hexcode>.+) is the hexcode for the color (?P<color>.+)', s)
>>> m.groupdict()
{'color': 'red', 'hexcode': '#ff0000'}
Note that if there's no match using your regular expression, the m
object here will be None
.
Upvotes: 2