首页 > 解决方案 > 正则表达式查找最小长度的句子

问题描述

我正在尝试创建一个正则表达式来查找具有最小长度的句子。

真的,我的条件是:

  1. 一个序列中必须至少有 5 个单词
  2. 序列中的单词必须是不同的
  3. 序列后面必须跟一些标点符号。

到目前为止我已经尝试过

^(\b\w*\b\s?){5,}\s?[.?!]$

如果我的示例文本是:

This is a sentence I would like to parse.

This is too short. 

Single word

Not not not distinct distinct words words.

Another sentence that I would be interested in. 

我想匹配字符串 1 和 5。

我正在使用 python re 库。我正在使用regex101进行测试,看起来我上面的正则表达式在回溯方面做了很多工作,所以我想那些熟悉正则表达式的人可能会有点震惊(我很抱歉)。

标签: pythonregex

解决方案


您可以使用以下正则表达式来识别满足所有三个条件的字符串:

^(?!.*\b(\w+)\b.+\b\1\b)(?:.*\b\w+\b){5}.*[.?!]\s*$

设置了大小写无关标志。

演示

Python 的正则表达式引擎执行以下操作。

^            # match beginning of line
(?!          # begin negative lookahead
  .+         # match 1+ chars
  \b(\w+)\b  # match a word in cap grp 1
  .+         # match 1+ chars
  \b\1\b     # match the contents of cap grp 1 with word breaks
)            # end negative lookahead
(?:          # begin non-cap grp
  .+         # match 1+ chars
  \b\w+\b    # match a word
)            # end non-cap grp
{5}          # execute non-cap grp 5 times
.*           # match 0+ chars
[.?!]        # match a punctuation char
\s*          # match 0+ whitespaces
$            # match end of line

推荐阅读