python正则表达式例子

#!/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")


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值