正則表達式中,如果想要不匹配某個字符可以使用如下
[^a]*
表示匹配除了a以外的所有字符
[^abc]*
表示匹配除了a、b、c以外的所有字符,注意這里不是abc字符串,而是a、b、c任何一個字符都不匹配
當我們要不匹配某個字符串或者中文詞組的時候,可以這樣用
((?!天空).)*
這個表示匹配出'天空'之外的所有字符
事實上,說正則表達式里不支持逆向匹配並不是百分之百的正確。就像這個問題,我們就可以使用否定式查找來模擬出逆向匹配。每個空字符都會檢查其前面的字符串是否不是'天空',如果不是,這.(點號)就是匹配捕捉這個字符。表達式(?!天空).只執行一次,所以,我們將這個表達式用括號包裹成組(group),然后用*(星號)修飾——匹配0次或多次,這種正則表達式的“查找”也叫做“zero-width-assertions”(零寬度斷言),因為它不會捕獲任何的字符,只是判斷
import re
string = '太陽天空照,花兒對我笑'
result = re.findall(r'^(?:(?!天空).)*?花兒.*$', string)
print(result)
# []
string = '太陽空中照,花兒對我笑'
result = re.findall(r'^(?:(?!天空).)*?花兒.*$', string)
print(result)
# ['太陽空中照,花兒對我笑']
比如我們要匹配今天的天氣,而不是明天的。即要匹配除tomorrow以外的單詞
import re
s1 = 'how is the weather today'
s2 = 'how is the weather tomorrow'
regex = r'(^.*weather(?:(?!tomorrow).)*$)'
result1 = re.findall(regex, s1)
result2 = re.findall(regex, s2)
print('result1: ', result1)
print('result2: ', result2)
# result1: ['how is the weather today']
# result2: []