我正在制作一个具备小型自学习功能的程序,现在我想从输出中获取“信息”,例如:
>>>#ff0000 is the hexcode for the color red
我想使用正则表达式
来过滤用户填写的句子is the hexcode for the color
,并提取颜色名称和十六进制代码。我在下面提供了一个小代码示例,展示我想实现的效果:
#main.pystrInput = raw_input("Please give a fact:")if "{0} is the hexcode for the color {1}" in strInput: # {0} 是颜色的名称 # {1} 是颜色的十六进制代码 print "You give me an color"if "{0} is an vehicle" in strInput: # {0} 是一种交通工具 print "You give me an vehicle"
使用正则表达式
是否可以实现这一点?使用正则表达式
的最佳方法是什么?
回答:
您可以在标准库文档中阅读关于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
。