How can i exclude a word with Regex?

Viewed 46

I want to find any word/characters, but not:

apple
apple 3

this is the string:

orange lemon 2 apple 3 pear

I tried this pattern but it didnt work:

\b(?!apple|apple \d+)\b\S+
2 Answers

You could use re.findall here to find all terms, followed by a list comprehension to filter that list:

inp = "orange lemon 2 apple 3 pear"
terms = re.findall(r'\w+(?: \d+)?', inp)
output = [x for x in terms if not re.search(r'^apple \d+', x)]
print(output)  # ['orange', 'lemon 2', 'pear']
st = 'orange lemon 2 apple 3 pear'

''.join(re.split(r'apple\s+\d?',st))

orange lemon 2  pear
Related