Partial match with negative lookahead using regex

2019-07-29 21:56发布

Using regex with negative lookahead I have to search a text file and identify a partially known line of text that is NOT followed by another partially known line of text. This is a simplified example of the text file:

blahblahblah.Name=qwqwqwqwqw
abracadabra.Surname=ererererer
zxzxzxzxzx.Name=kmkmkmkmkmkm
oioioioi.Name=dfdfdfdfdfdf
popopopopopopo.Surname=lklklklklklklk

In the sample above you can see the pattern where a line with Name should always follow by a line with Surname, but sometimes it doesn't happen. I have to identify those "Name lines" which are not followed by the "Surname lines".

I am using File Search in Eclipse (it supports regex).

This is one of my best attempts, I guess, but it still doesn't do the trick:

(Name.*\n)(?!.*Surname)

Please share your thoughts. Kind regards.

2条回答
萌系小妹纸
2楼-- · 2019-07-29 22:24

.*\bName=.*\n(?!.*\bSurname=) will do.

Below is an example in Python.

import re
s='''blahblahblah.Name=qwqwqwqwqw
abracadabra.Surname=ererererer
zxzxzxzxzx.Name=kmkmkmkmkmkm
oioioioi.Name=dfdfdfdfdfdf
popopopopopopo.Surname=lklklklklklklk'''
print(re.findall(r'\bName=.*\n(?!.*\bSurname=)', s))

This outputs:

['zxzxzxzxzx.Name=kmkmkmkmkmkm\n']
查看更多
爷、活的狠高调
3楼-- · 2019-07-29 22:30

Here is a line oriented negative lookahead:

^(.*\.Name.*)[\r\n]+(?!.*\.Surname)

Demo

查看更多
登录 后发表回答