首页 > 解决方案 > Python正则表达式集合中的0个或多个单词

问题描述

我有一大段文字,我试图在其中寻找一个短语。该短语可以以多种不同的方式构造。

  1. 首先我想从一组词中找一个词,我们称它为set 1。
  2. 之后必须有一个空格或逗号(或者可能是其他分隔单词的东西)
  3. 那么集合 2 中可能有 0 个或多个单词
  4. 再跟上面第 2 点中的单词分隔字符
  5. 最后应该有第3集的一个词

理想情况下,所有这些都应该在同一个句子中。

设置 1 =(Potential|Ability|Possibility|need|requires|needs|plenty|for|Needing|Requiring)

设置 2 =(for|to|of|full|a|be|complete|Internal)

设置 3 =(renovate|improve|modernise|modernize|update|renovating|improving|modernising|modernizing|updating|potential|project|renovation)

所以我有这个正则表达式

(Potential|Ability|Possibility|need|requires|needs|plenty|for|Needing|Requiring)[ ,]*(for|to|of|full|a|be|complete|Internal)[ ,]*(renovate|improve|modernise|modernize|update|renovating|improving|modernising|modernizing|updating|potential|project|renovation)

现在这将匹配一个短语,其中有来自 set 2 的 0 或 1 个单词,但如果有多个单词则不匹配。例如“为某人添加自己的印章提供了绝佳的机会,因为该物业需要在整个过程中进行全面翻新。”

只要我在“完成”之前添加“a”,它就会失败。就像我添加另一个“完整”一样。

如何指定从集合中查找 0 个或多个单词?

标签: pythonregex

解决方案


第 1 组:匹配第 1 组中的任何单词,并带有 1 个分隔符。

(Potential|Ability|Possibility|need|requires|needs|plenty|for|Needing|Requiring)[ ,]

第 2 组:匹配第 2 组中的任何单词,用 1 个分隔符匹配 0 次或多次。

((for|to|of|full|a|be|complete|Internal)[ ,])*

第 3 组:匹配第 3 组中的任何单词

(renovate|improve|modernise|modernize|update|renovating|improving|modernising|modernizing|updating|potential|project|renovation)

满的:

(Potential|Ability|Possibility|need|requires|needs|plenty|for|Needing|Requiring)[ ,]((for|to|of|full|a|be|complete|Internal)[ ,])*(renovate|improve|modernise|modernize|update|renovating|improving|modernising|modernizing|updating|potential|project|renovation)

推荐阅读