正则表达式和模式

时间:2014-04-04 07:23:02

标签: python regex

他可以看到使用RE

进行电子邮件匹配的简单脚本
# Exercise: make a regular expression that will match an email
def test_email(your_pattern):
    pattern = re.compile(r"^(john|python-list|wha)")
    emails = ["john@example.com", "python-list@python.org", "wha.t.`1an?ug{}ly@email.com"]
    for email in emails:
        if not re.match(pattern, email):
            print "You failed to match %s" % (email)
        elif not your_pattern:
            print "Forgot to enter a pattern!"
        else:
            print "%s was found in the %s" %(str(pattern),email)
pattern = r"^(john|python-list|wha)" # Your pattern here!
test_email(pattern)

正如你在这里看到的那样,作为本地和全球

,已经提到了模式
variables. Eventually I've obtained results like
<_sre.SRE_Pattern object at 0x223dba0> was found in the john@example.com
<_sre.SRE_Pattern object at 0x223dba0> was found in the python-list@python.org
<_sre.SRE_Pattern object at 0x223dba0> was found in the wha.t.`1an?ug{}ly@email.

如何在relusts中显示真实的模式,而不是像Pattern_object那样显示字符串?

为什么我定义一个类似下面例子的模式,没有找到模式?

pattern = re.compile(r"$(org|com)") # find strings which end on the 'com' or 'org'

1 个答案:

答案 0 :(得分:1)

您需要打印匹配的组。您现在正在打印搜索模式对象,这不是匹配项。您应该存储匹配(如果存在)并打印出来。

# Exercise: make a regular expression that will match an email
def test_email(your_pattern):
    pattern = re.compile(r"^(john|python-list|wha)")
    emails = ["john@example.com", "python-list@python.org", "wha.t.`1an?ug{}ly@email.com"]
    for email in emails:
        match = re.match(pattern, email)
        if not match:
            print "You failed to match %s" % (email)
        elif not your_pattern:
            print "Forgot to enter a pattern!"
        else:
            print "%s was found in the %s" %(match.groups(), email)
pattern = r"^(john|python-list|wha)" # Your pattern here!
test_email(pattern)

另请注意,您正在覆盖函数第一行中的模式。您可能希望将其更改为:

def test_email(your_pattern):
    pattern = your_pattern # See here.
    emails = ["john@example.com", "python-list@python.org", "wha.t.`1an?ug{}ly@email.com"]
    for email in emails:
        match = re.match(pattern, email)
        if not match:
            print "You failed to match %s" % (email)
        elif not your_pattern:
            print "Forgot to enter a pattern!"
        else:
            print "%s was found in the %s" %(match.groups(), email)

请注意re.match将从该行的开头匹配,因此如果您需要匹配来说my email is john@example.com,则需要使用re.search

有关search() vs. match()

的更多信息

演示:

>>> pattern = r"^(john|python-list|wha)" # Your pattern here!
>>> test_email(pattern)
('john',) was found in the john@example.com
('python-list',) was found in the python-list@python.org
('wha',) was found in the wha.t.`1an?ug{}ly@email.com
>>>