字符串掩码和正则表达式的偏移量

Ale*_*rad 3 python regex regex-negation

我有一个字符串,我尝试创建一个正则表达式掩码N,给出一个偏移量,显示单词的数量.假设我有以下字符串:

"The quick, brown fox jumps over the lazy dog."

我想在当时显示3个单词:

offset 0:"The quick, brown"
offset 1:"quick, brown fox"
offset 2:"brown fox jumps"
offset 3:"fox jumps over"
offset 4:"jumps over the"
offset 5:"over the lazy"
offset 6:"the lazy dog."

我正在使用Python,我一直在使用以下简单的正则表达式来检测3个单词:

>>> import re
>>> s = "The quick, brown fox jumps over the lazy dog."
>>> re.search(r'(\w+\W*){3}', s).group()
'The quick, brown '

但我无法弄清楚如何有一种面具来显示接下来的3个单词而不是开始的单词.我需要保持标点符号.

pol*_*nts 5

前缀匹配选项

您可以通过使用变量前缀正则表达式来跳过第一个offset单词,并将单词triplet捕获到一个组中来完成此工作.

所以像这样:

import re
s = "The quick, brown fox jumps over the lazy dog."

print re.search(r'(?:\w+\W*){0}((?:\w+\W*){3})', s).group(1)
# The quick, brown 
print re.search(r'(?:\w+\W*){1}((?:\w+\W*){3})', s).group(1)
# quick, brown fox      
print re.search(r'(?:\w+\W*){2}((?:\w+\W*){3})', s).group(1)
# brown fox jumps 
Run Code Online (Sandbox Code Playgroud)

我们来看看模式:

 _"word"_      _"word"_
/        \    /        \
(?:\w+\W*){2}((?:\w+\W*){3})
             \_____________/
                group 1
Run Code Online (Sandbox Code Playgroud)

这就是它所说的:匹配2单词,然后捕获到组1,匹配3单词.

(?:...)结构被用于为重复分组,但他们非捕获.

参考


关于"单词"模式的注释

应该说,\w+\W*对于"单词"模式来说,这是一个糟糕的选择,如下例所示:

import re
s = "nothing"
print re.search(r'(\w+\W*){3}', s).group()
# nothing
Run Code Online (Sandbox Code Playgroud)

没有3个单词,但正则表达式无论如何都能匹配,因为\W*允许空字符串匹配.

也许更好的模式是这样的:

\w+(?:\W+|$)
Run Code Online (Sandbox Code Playgroud)

也就是说,\w+后面跟着\W+字符串的一个或结尾$.


捕获前瞻选项

正如Kobi在评论中所建议的那样,这个选项更简单,因为你只有一个静态模式.它用于findall捕获所有匹配项(请参阅ideone.com):

import re
s = "The quick, brown fox jumps over the lazy dog."

triplets = re.findall(r"\b(?=((?:\w+(?:\W+|$)){3}))", s)

print triplets
# ['The quick, brown ', 'quick, brown fox ', 'brown fox jumps ',
#  'fox jumps over ', 'jumps over the ', 'over the lazy ', 'the lazy dog.']

print triplets[3]
# fox jumps over 
Run Code Online (Sandbox Code Playgroud)

这是如何工作的,它匹配零宽度字边界\b,使用先行来捕获组1中的3个"单词".

    ______lookahead______
   /      ___"word"__    \
  /      /           \    \
\b(?=((?:\w+(?:\W+|$)){3}))
     \___________________/
           group 1
Run Code Online (Sandbox Code Playgroud)

参考