问题
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.
回答1:
.*\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']
回答2:
Here is a line oriented negative lookahead:
^(.*\.Name.*)[\r\n]+(?!.*\.Surname)
Demo
来源:https://stackoverflow.com/questions/51199952/partial-match-with-negative-lookahead-using-regex