Python 正则表达式和模式
他说,您可以使用RE查看电子邮件匹配的简单脚本Python 正则表达式和模式,python,regex,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@e
# 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)
正如你在这里看到的,patter被反复提到,它既是本地的,也是全球的
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.
您需要打印匹配的组。您现在正在打印不匹配的搜索模式对象。您应该存储匹配项(如果存在),并打印它
# 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
将从行首开始匹配,因此如果您需要从开始匹配,请说,我的电子邮件是john@example.com
,您需要使用re.search
有关
演示:
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)
>>> 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
>>>