使用正则表达式进行局部匹配,负向提前 [英] 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
在上面的示例中,您可以看到以下模式:带有 Name 的行应始终跟有带有 Surname 的行,但有时不会发生.我必须确定那些名称行"后面没有姓氏行".
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".
我正在Eclipse中使用文件搜索(它支持正则表达式).
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:
(名称.* \ n)(?!.*姓氏)
(Name.*\n)(?!.*Surname)
请分享您的想法. 亲切的问候.
Please share your thoughts. Kind regards.
推荐答案
.*\bName=.*\n(?!.*\bSurname=)
可以.
以下是Python中的示例.
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))
这将输出:
['zxzxzxzxzx.Name=kmkmkmkmkmkm\n']
这篇关于使用正则表达式进行局部匹配,负向提前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!