我正在制作一个程序,它有一个很小的自学方式,但现在我想从输出中获得“信息”,比如:
>>>#ff0000 is the hexcode for the color red我想使用reggular expressions过滤用户填充这个句子的is the hexcode for the color,并检索颜色的名称和十六进制代码。我已经在我想要的工作方式下面放了一个小代码:
#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"这在reggular expressions中是可能的吗?用reggular expressions做这件事的最好方法是什么
发布于 2015-05-15 11:28:14
您可以在标准库文档中阅读有关Python中的正则表达式的内容。在这里,我使用命名组将匹配的值存储到具有您选择的键的字典结构中。
>>> 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'}注意,如果使用正则表达式没有匹配,这里的m对象将是None。
https://stackoverflow.com/questions/30258235
复制相似问题