Make python re.sub look multiple times

前端 未结 2 1805
南笙
南笙 2021-01-29 07:46

Suppose I have the following code:

s = \'cucumber apple tomato\'

def f(match):
    if match.group(2) not in (\'apple\', ):
        return \'%s (%s)\' % (match.gr         


        
2条回答
  •  萌比男神i
    2021-01-29 08:21

    This is based on the information you've given in the comments so may not be exactly what you're looking for but:

    There can be any number of words: 'cucumber apple tomato tomato apple cucumber tomato tomato' and the output should be 'cucumber apple (tomato) tomato apple (cucumber) tomato (tomato)'

    This regex will capture all non space characters after "apple" and before the end of the line while ignoring words finishing in "apple" and allowing it to be the first in the line.

    (?:^| )apple ([^ ]*)|([^ ]+)$
    

    For the example string
    "apple cucumber pineapple tomato tomato apple cucumber tomato tomato"
    it will select
    "apple cucumber pineapple tomato tomato apple cucumber tomato tomato"

提交回复
热议问题