#!/usr/bin/env python
#--*-- coding:utf-8 --*--
import re
def print_match(pattern_str, match_str):
"""打印match匹配的字段"""
m = re.match(pattern_str, match_str)
if m :
print("YES -->pattern_str=[ %s ] in match_str[ %s ], group=[ %s ], groups=[ %s ]" % (match_str, pattern_str, m.group(), m.groups()))
else :
print("NO -->pattern_str=[ %s ] in match_str[ %s ]" % (match_str, pattern_str))
def print_search(pattern_str, match_str):
"""打印search匹配的字段"""
m = re.search(pattern_str, match_str)
if m :
print("YES -->pattern_str=[ %s ] in match_str[ %s ], group=[ %s ]" % (match_str, pattern_str, m.group()))
else :
print("NO -->pattern_str=[ %s ] in match_str[ %s ]" % (match_str, pattern_str))
#match 和 serch
print_match("foo", "seafood")
print_search("foo", "food on the table")
#或者
bt = "bat|bet|bit"
print_match(bt, "bat")
print_match(bt, "bit")
print_search(bt, "bit")
#邮箱
print_match("\w+@(\w+\.)?\w+\.com", "nobody@xxx.com")
print_match("\w+@(\w+\.)?\w+\.com", "nobody@www.xxx.com")
print_match("\w+@(\w+\.)?\w+\.com", "nobody@www.www.xxx.com")
#分组
print_match("(\w\w\w)-(\d\d\d)", "abc-123")
#替换
print(re.sub("MAN_NAME", "Mr.smith", "MAN_NAME ,Welcome join us!"))
print(re.sub("WOMAN_NAME", "Mis.angle", "WOMAN_NAME ,Welcome join us!"))
print(re.subn("WOMAN_NAME", "Mis.angle", "WOMAN_NAME ,Welcome join us!"))
#截取
print(re.split(":", "sp1:sp2:sp3"))
#原始字符串
print_match("\bblow", "blow")
print_match(r"\bblow", "blow")
#贪婪与非贪婪
print_match(".+(\d+-\d+-\d+)", "This is just a test::2013-06-06")
print_match(".+?(\d+-\d+-\d+)", "This is just a test::2013-06-06")
python正则表达式例子
最新推荐文章于 2024-01-30 21:44:08 发布