Skip to main content
 首页 » 编程设计

Python,正则表达式负后视行为

2025年05月04日21freeliver54

我有一个正则表达式,可以在一行中找到最多 10 个单词。也就是说,它应该包括换行符之前的单词,而不是换行符之后的单词。我正在使用带有“\n”的负面回顾。

a = re.compile(r"((\w)+[\s /]){0,10}(?<!\n)") 
r = a.search("THe car is parked in the garage\nBut the sun is shining hot.") 

当我执行此正则表达式并调用方法 r.group() 时,我得到了整个句子但最后一个包含句点的单词。我只期待新行之前的完整字符串。即,“汽车停在车库里\n”。 带着负面的目光我在这里犯的错误是什么...?

请您参考如下方法:

我不知道你为什么要使用负前瞻。您是说换行前最多需要 10 个单词。下面的正则表达式应该可以工作。它使用积极的前瞻来确保在单词之后是换行符。此外,在搜索单词时,请使用 `b\w+\b` 而不是您正在使用的内容。

/(\b\w+\b)*(?=.*\\n)/ 

python :

result = re.findall(r"(\b\w+\b)*(?=.*\\n)", subject) 

解释:

# (\b\w+\b)*(?=.*\\n) 
#  
# Match the regular expression below and capture its match into backreference number 1 «(\b\w+\b)*» 
#    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
#    Note: You repeated the capturing group itself.  The group will capture only the last iteration.  Put a capturing group around the repeated group to capture all iterations. «*» 
#    Assert position at a word boundary «\b» 
#    Match a single character that is a “word character” (letters, digits, etc.) «\w+» 
#       Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
#    Assert position at a word boundary «\b» 
# Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=.*\\n)» 
#    Match any single character that is not a line break character «.*» 
#       Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» 
#    Match the character “\” literally «\\» 
#    Match the character “n” literally «n» 

您可能还希望考虑这样一个事实,即您的字符串中可能没有\n。