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

1 python 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"
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*lak 7

这个:

the( cat( sat( on( the( mat)?)?)?)?)?
Run Code Online (Sandbox Code Playgroud)

会回答你的问题.删除"可选组"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")
Run Code Online (Sandbox Code Playgroud)

您可能希望添加一些前置条件,例如行锚的开头,以防止表达式匹配最后一行中的第二个"the":

^the( cat( sat( on( the( mat)?)?)?)?)?
Run Code Online (Sandbox Code Playgroud)

编辑:如果你添加一个后置条件,比如行尾锚,在最后一个例子中将完全阻止匹配,也就是说,最后一个例子根本不匹配:

the( cat( sat( on( the( mat)?)?)?)?)?$
Run Code Online (Sandbox Code Playgroud)

提示的积分转到VonC.谢谢!

后置条件当然可能是你期望跟随比赛的其他事情.

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

the( cat( sat( on( the( mat)?)?)?)?)
Run Code Online (Sandbox Code Playgroud)

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