使用 Python 我需要删除多行字符串中的所有字符,直到第一次出现给定模式。在 Perl 中,这可以使用正则表达式来完成,例如:
#remove all chars up to first occurrence of cat or dog or rat
$pattern = 'cat|dog|rat'
$pagetext =~ s/(.*?)($pattern)/$2/xms;
在 Python 中执行此操作的最佳方法是什么?
最佳答案
>>> import re
>>> s = 'hello cat!'
>>> m = re.search('cat|dog|rat', s)
>>> s[m.start():]
'cat!'
当然,您需要考虑实际解决方案中没有匹配项的情况。
或者,更简洁:
>>> import re
>>> s = 'hello cat!'
>>> p = 'cat|dog|rat'
>>> re.sub('.*?(?=%s)' % p, '', s, 1)
'cat!'
对于多行,使用 re.DOTALL
标志。
关于python - 删除多行字符串中直到给定模式的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2658101/