Skip to main content
 首页 » 编程设计

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

2025年05月04日14JustinYoung

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

这可以用 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”不匹配,因此第一行也不会匹配。