首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:自学习程序的Reggular表达式过滤

Python:自学习程序的Reggular表达式过滤
EN

Stack Overflow用户
提问于 2015-05-15 11:21:21
回答 1查看 32关注 0票数 0

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

代码语言:javascript
复制
>>>#ff0000 is the hexcode for the color red

我想使用reggular expressions过滤用户填充这个句子的is the hexcode for the color,并检索颜色的名称和十六进制代码。我已经在我想要的工作方式下面放了一个小代码:

代码语言:javascript
复制
#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做这件事的最好方法是什么

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-15 11:28:14

您可以在标准库文档中阅读有关Python中的正则表达式的内容。在这里,我使用命名组将匹配的值存储到具有您选择的键的字典结构中。

代码语言:javascript
复制
>>> 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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30258235

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档