您的位置:首页 > 编程语言 > Python开发

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

2014-07-26 22:45 691 查看
例一、匹配以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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: