Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python正则表达式中附加一个负lookbehind列表?_Python_Regex - Fatal编程技术网

如何在python正则表达式中附加一个负lookbehind列表?

如何在python正则表达式中附加一个负lookbehind列表?,python,regex,Python,Regex,我试图用regex split将一段话分成几个句子,并尝试使用此处发布的第二个答案: 但我有一个缩略语列表,即使有句号,我也不想结束这个句子。但我不知道如何将它正确地附加到正则表达式中。我正在阅读一个文件中的缩略语,其中包含St.Ms.Dr.先生(每行一个)这样的术语。简短回答:你不能,除非所有的lookback断言都是相同的固定宽度(在你的例子中可能不是这样;你的例子中只包含两个字母的缩略语,但是Mrs.会破坏你的正则表达式) 这是当前Python正则表达式引擎的一个限制 详细回答: 您可以

我试图用regex split将一段话分成几个句子,并尝试使用此处发布的第二个答案:


但我有一个缩略语列表,即使有句号,我也不想结束这个句子。但我不知道如何将它正确地附加到正则表达式中。我正在阅读一个文件中的缩略语,其中包含St.Ms.Dr.先生(每行一个)这样的术语。

简短回答:你不能,除非所有的lookback断言都是相同的固定宽度(在你的例子中可能不是这样;你的例子中只包含两个字母的缩略语,但是
Mrs.
会破坏你的正则表达式)

这是当前Python正则表达式引擎的一个限制

详细回答:

您可以编写一个类似于
(?s)(?)的正则表达式,在lookbehind断言的每个交替部分填充所需的
s,以使它们的宽度相同。但是,在某些情况下,这可能会失败,例如当段落以
Mr.
开头时

无论如何,您在这里使用的工具不正确。最好使用为工作设计的工具,例如

如果您一直使用正则表达式(太糟糕了!),那么您可以尝试使用
findall()
方法,而不是
split()

将匹配以
结尾的句子(可选后跟空格),并且可能不包含点,除非前面有一个允许的缩写

>>> import re
>>> s = "My name is Mr. T. I pity the fool who's not on the A-Team."
>>> re.findall(r"(?:(?:\b(?:Mr|Ms|Dr|Mrs|St)\.)|[^.])+\.\s*", s)
['My name is Mr. T. ', "I pity the fool who's not on the A-Team."]

我不会直接回答你的问题,但这篇文章应该包含足够的信息,让你可以为你的问题编写一个有效的正则表达式。

可以添加一个消极的look behind列表。记住look behind是零宽度的,这意味着您可以将任意多个look behind放在彼此旁边,并且您仍然从同一位置向后看。只要您不需要使用“many”量词(例如
*
+
{n,}
)在“回头看”中,一切都应该很好(?)

因此正则表达式可以这样构造:

(?<!list )(?<!of )(?<!words )(?<!not )(?<!allowed )(?<!to )(?<!precede )pattern\w+
(?
这有点太冗长了。不管怎样,我写这篇文章只是为了证明可以在固定字符串列表中查找后面的内容

运行示例:

>>> s = 'something patterning of patterned crap patternon not patterner, not allowed patternes to patternsses, patternet'
>>> re.findall(r'(?<!list )(?<!of )(?<!words )(?<!not )(?<!allowed )(?<!to )(?<!precede )pattern\w+', s)
['patterning', 'patternon', 'patternet']
>>s='patterned crap patterneon非patterner,不允许patternes到patternses,patternet'

>>>re.findall(r'(?我只能使用python stdlib。那么,有没有其他方法可以在不使用lookbehinds的情况下考虑缩写?“这是当前python正则表达式引擎的一个限制。”–你有什么东西让我读一下这个限制吗?@poke:the read:“
(?@TimPietzcker:Look behind for a list of fixed text可以完成(在某种程度上,有某些限制)。我已将我的长文本列表格式化为一个长字符串,如下所示:(?@user2017502:使用此选项时,请查看捕获。对于案例
Mr.\ux
是空格-在
和名称之间有2个空格)
>>> s = 'something patterning of patterned crap patternon not patterner, not allowed patternes to patternsses, patternet'
>>> re.findall(r'(?<!list )(?<!of )(?<!words )(?<!not )(?<!allowed )(?<!to )(?<!precede )pattern\w+', s)
['patterning', 'patternon', 'patternet']