python - 正则表达式查找最小长度的句子
问题描述
我正在尝试创建一个正则表达式来查找具有最小长度的句子。
真的,我的条件是:
- 一个序列中必须至少有 5 个单词
- 序列中的单词必须是不同的
- 序列后面必须跟一些标点符号。
到目前为止我已经尝试过
^(\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进行测试,看起来我上面的正则表达式在回溯方面做了很多工作,所以我想那些熟悉正则表达式的人可能会有点震惊(我很抱歉)。
解决方案
您可以使用以下正则表达式来识别满足所有三个条件的字符串:
^(?!.*\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
推荐阅读
- axios - 使用 axios 和 vuex 响应的空数据
- excel-formula - 转置具有多个字段的大数据
- node.js - 寻找一种将新字段添加到嵌套 redis 对象的更好方法
- windows - 如何修复这个 Flutter 错误,以便在 Android 上运行该应用程序?
- ruby-on-rails - 无法启动 Rails 服务器 - 一堆错误
- javascript - 关于如何在身份验证中实施挑战(2 因素身份验证等)的任何建议
- android - 如何设置环境变量以便NDK中的CMakelists.txt可以访问?
- c# - C# 中的零星 SMTP 电子邮件发送失败
- r - 如何找出有多少受访者至少缺少 3 个回答?
- php - 我尝试在 Mac OS X Big Sur 环境中使用 Xdebug v3.1.0,它无法启动套接字,Operation now in progress (19),任何人都可以帮助我吗?