正則表達式(Regular expression)可用來檢查文本中是否包含指定模式的字符串,通常是按行來處理(POSIX標準),因為.操作符通常不匹配換行符,如果要匹配多行怎么處理呢?本文介紹正則表達式跨行匹配實現方法。
1. sed 命令刪除多行
測試文檔test.txt內容如下:
start
test1
test2
end
刪除 start 和 end 之間的內容
# 包括`start` 和 `end`
sed -i '/start/,/end/d' test.txt
# 不包括`start` 和 `end`
sed -i '/start/,/end/{{//!d;};}' test.txt
2. Python正則表達式匹配多行
Python中匹配多行方法如下:
①re.DOTALL或者re.S參數
import re
data = "1nstartntest1ntest2nendn2"
reg1 = r"start.*end"
reg2 = r"start(.*)end"
res1 = re.findall(reg1, data, flags=re.S)
print(res1)
res2 = re.findall(reg2, data, flags=re.DOTALL)
print(res2)
執行結果:
['startntest1ntest2nend']
['ntest1ntest2n']
② 表達式(.|n|r)*
import re
data = "1nstartntest1ntest2nendn2"
reg3 = r"start((.|n|r)*)end"
res = re.findall(reg3, data)
print(res)
執行結果:
[('ntest1ntest2n', 'n')]
③ 表達式[sS]*
import re
data = "1nstartntest1ntest2nendn2"
reg4 = r"start([sS]*)end"
res = re.findall(reg4, data)
print(res)
執行結果:
['ntest1ntest2n']
④ 表達式(?s)
import re
data = "1nstartntest1ntest2nendn2"
reg5 = r"(?s)start(.*)end"
res = re.findall(reg5, data)
print(res)
reg5 = r"(?s)start.*end"
res = re.findall(reg5, data)
print(res)
執行結果:
['ntest1ntest2n']
['startntest1ntest2nend']
參考:
- https://stackoverflow.com/questions/159118/how-do-i-match-any-character-across-multiple-lines-in-a-regular-expression
--THE END--