我想通过使用正则表达式来减少我必须编写的模式数量,该正则表达式在出现在字符串中时提取任何或所有模式。
这可以用 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/