简体   繁体   中英

Partial match with negative lookahead using regex

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.

Here is a line oriented negative lookahead:

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

Demo

.*\\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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM