[Python]几个正则表达式匹配的例子

例一、匹配以abc开头的单词。

text = "abcthis is thatabc colvin"
pat = r"\b(?=abc)\w*"
print re.findall(pat,text)
>>>

['abcthis']

例二、匹配不是以abc开头的单词。

text = "abcthis is thatabc colvin"
pat2 = r"\b(?!abc)\w+"
print re.findall(pat2,text)
>>>

['is', 'thatabc', 'colvin']

text = "abcthis is thatabc colvin"
pat3 = r"(?<!\w)(?=\w)(?!abc)\w+"
print re.findall(pat3,text)
>>>

['is', 'thatabc', 'colvin']

print re.findall(r"\b[^\Wa][^\Wb]?[^\Wc]?\w*\b","abcthis is abcthat colvin")
>>>

['is', 'colvin']

def getpat(str):
    pat = r"".join(["[^\W"+y+"]"+"?"*(x>0) for x,y in enumerate(str)])
    pat = r"\b"+pat+r"\w*\b"
    return pat

pat = getpat("abc")
print re.findall(pat,text)
>>>

['is', 'thatabc', 'colvin']

例三、匹配不包含abc的单词。

text = "abcthis is thatabc colvin"
pat4 = r"\b(((?!abc)\w)+)\b"
print re.findall(pat4,text)
>>>

[('is', 's'), ('colvin', 'n')]

例四、对字符串中的数值每3位添加一个小数点

13324323  =>  13.324.323  

This is 1965th    =>  This is 1965th

333   =>  333

print re.sub(r'(?<=\d)(?=(\d\d\d)+\b)', '.', str('435453454534'))
>>>

435.453.454.534



 




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值