Python:用于自学习程序的正则表达式过滤

2024-10-02 16:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个程序,它有一个小的自我学习方式,但现在我想从输出中获得“信息”,如:

>>>#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的最佳方法是什么


Tags: ofthe代码inanforifis
1条回答
网友
1楼 · 发布于 2024-10-02 16:31:12

您可以在标准库文档中阅读regular expressions in 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

相关问题 更多 >