例一、匹配以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"(?
>>>
['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