python - 正则表达式:当字符串包含正则表达式模式的一部分时匹配字符串的一部分

标签 python regex

我想通过使用正则表达式来减少我必须编写的模式数量,该正则表达式在出现在字符串中时提取任何或所有模式。

这可以用 Regex 实现吗?

E.g. Pattern is: "the cat sat on the mat"

I would like pattern to match on following strings:
"the"
"the cat"
"the cat sat"
...
"the cat sat on the mat"

但它不应该匹配下面的字符串,因为虽然有些词匹配,但它们被一个不匹配的词分开了: “狗坐着”

最佳答案

这个:

the( cat( sat( on( the( mat)?)?)?)?)?

会回答你的问题。删除“可选组”parens“(...)?”对于不是可选的部分,为必须匹配在一起的事物添加额外的组。

the                       // complete match
the cat                   // complete match
the cat sat               // complete match
the cat sat on            // complete match
the cat sat on the        // complete match
the cat sat on the mat    // complete match
the dog sat on the mat    // two partial matches ("the")

您可能想要添加一些前提条件,例如行 anchor 的开头,以防止表达式匹配最后一行中的第二个“the”:

^the( cat( sat( on( the( mat)?)?)?)?)?

编辑:如果您添加后置条件,例如行尾 anchor ,将完全阻止最后一个示例的匹配,也就是说,最后一个示例不会匹配全部:

the( cat( sat( on( the( mat)?)?)?)?)?$

小费的来源转到VonC .谢谢!

当然,后置条件可能是您希望在比赛之后发生的其他事情。

或者,您删除最后一个问号:

the( cat( sat( on( the( mat)?)?)?)?)

但请注意:这会使单个“the”不匹配,因此第一行也不会匹配。

关于python - 正则表达式:当字符串包含正则表达式模式的一部分时匹配字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/490762/

相关文章:

python - Numpy 没有正确求解矩阵方程

python - 使用 python 将结果保存在 YAML 文件中

python - 为 Python 安装 pip 时出错

python - Python 中的快速多重搜索和替换

php - preg_replace 删除除破折号、字母、数字、空格和下划线以外的所有字符

python - 正则表达式捕获任何数字超过 4 位数字之前的重叠匹配项

python - python中未使用的变量命名

python - 如何使用 Pandas 基于多个字符串索引拆分列

Javascript正则表达式从特定单词中获取数字部分

php - 在 Laravel 中使用 Eloquent ORM 使用 'not regexp' 执行数据库搜索