xXpyXx
xXpyXx

Reputation: 11

How can i exclude a word with Regex?

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+

Upvotes: 0

Views: 83

Answers (2)

LetzerWille
LetzerWille

Reputation: 5668

st = 'orange lemon 2 apple 3 pear'

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

orange lemon 2  pear

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522719

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']

Upvotes: 1

Related Questions