[英]find pattern on multiline python
我花了兩天時間嘗試構建正則表達式,以發現兩個單詞/數字在不同的行上依次出現。 我有一個文本如下的文件:
1 [pid 29743] 18:58:19 prctl(PR_CAPBSET_DROP, 0x9, 0, 0, 0 <unfinished ...>
2 [pid 29746] 18:58:19 <... mprotect resumed> ) = 0
3 [pid 29743] 18:58:19 <... prctl resumed> ) = 0
4 [pid 615] 18:58:19 <... ioctl resumed> , 0xffffffffffb4f054) = 0
5 [pid 29743] 18:58:19 prctl(PR_CAPBSET_READ, 0xa, 0, 0, 0 <unfinished ...>
6 [pid 615] 18:58:19 ioctl(13, 0x40047703 <unfinished ...>
7 [pid 29743] 18:58:19 <... prctl resumed> ) = 1
8 [pid 29746] 18:58:19 mprotect(0xfffffffff4ae2000, 4096, PROT_NONE <unfinished ...>
9 [pid 29743] 18:58:19 prctl(PR_CAPBSET_DROP, 0xa, 0, 0, 0 <unfinished ...>
10 [pid 615] 18:58:19 <... ioctl resumed> , 0x7fd19062e0) = 0
11 [pid 29743] 18:58:19 <... prctl resumed> ) = 0
12 [pid 29746] 18:58:19 <... mprotect resumed> ) = 0
13 [pid 29743] 18:58:19 prctl(PR_CAPBSET_READ, 0xb, 0, 0, 0 <unfinished ...>
14 [pid 29746] 18:58:19 ioctl(13, 0x40047703,
<unfinished ...>
15 [pid 29743] 18:58:19 <... prctl resumed> ) = 1
16 [pid 615] 18:58:19 <... ioctl resumed> , 0x7fd19064b0) = 0
我正在尋找兩個順序出現在文本上的值0x7fd19062e0和0x7fd19064b0。 它們出現在第10行和第16行。我想構建一個正則表達式,告訴我是否依次出現。這是我的代碼
file = open("text.txt", a+)
for line in file:
text += line
if re.findall(r"^.*0x7fd19062e0.*0x7fd19064b0", text, re.M):
print 'found a match!'
else:
print 'no match'
re.M
修改^
和$
錨點的行為。 對於“點匹配換行”選項,您需要re.S
另外,如果您只想查找是否存在匹配項,請不要使用re.findall()
:
file = open("text.txt") # why append mode?
text = file.read() # no need to build the string line by line
if re.search(r"\b0x7fd19062e0\b.*\b0x7fd19064b0\b", text, re.S):
print 'found a match!'
else:
print 'no match'
請注意,我添加了單詞邊界錨以確保僅匹配整個十六進制數字(否則,可以進行更長數字的子匹配)。 這可能與您的情況無關,但可能是個好習慣。
無需RE:
f = open('text.txt')
numerated_lines = enumerate(f.readlines())
lines_with_pattern = filter(lambda l: '0x7fd19062e0' in l[1], enumerated_lines)
pairs = zip(lines, lines[1:])
result = filter(lambda p: p[0][0]+1 == p[1][0], pairs)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.