删除多行字符串中的所有字符,直到给定的模式

big*_*num 3 python regex string

使用Python我需要删除多行字符串中的所有字符,直到给定模式的第一个出现.在Perl中,这可以使用正则表达式来完成,例如:

#remove all chars up to first occurrence of cat or dog or rat
$pattern = 'cat|dog|rat' 
$pagetext =~ s/(.*?)($pattern)/$2/xms; 
Run Code Online (Sandbox Code Playgroud)

在Python中使用它的最佳方法是什么?

Max*_*keh 5

>>> import re
>>> s = 'hello cat!'
>>> m = re.search('cat|dog|rat', s)
>>> s[m.start():]
'cat!'
Run Code Online (Sandbox Code Playgroud)

当然,您需要考虑真实解决方案中无法匹配的情况.

或者,更干净:

>>> import re
>>> s = 'hello cat!'
>>> p = 'cat|dog|rat'
>>> re.sub('.*?(?=%s)' % p, '', s, 1)
'cat!'
Run Code Online (Sandbox Code Playgroud)

对于多行,请使用re.DOTALL标志.