Partial match with negative lookahead using regex

久未见 提交于 2019-12-11 08:52:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!