Search code examples
pythonpython-3.xregexstringpython-re

re.sub replace substring between two specific characters multiple times


Given a string s as follows, I want to remove substring between but and ball multiple times:

s = 'I like sport, but I don\'t like football; I like sport, but I don\'t like basketball'
re.sub('but.*ball', '', s, flags=re.MULTILINE)

Out:

'I like sport, '

How could I get the expected result like this:

'I like sport, I like sport'

Solution

  • Try adding a question mark:

    >>> re.sub('but.*?ball|[,;]', '', s, flags=re.MULTILINE).strip()
    'I like sport  I like sport'
    >>>