Thursday 13 August 2020

Match words that don't start with a certain letter using regex

 

With regex

Use the negative set [^\Wt] to match any alphanumeric character that is not t. To avoid matching subsets of words, add the word boundary metacharacter, \b, at the beginning of your pattern.

Also, do not forget that you should use raw strings for regex patterns.

import re

text = 'this is a test'
match = re.findall(r'\b[^\Wt]\w*', text)

print(match) # prints: ['is', 'a']

See the demo here.

Without regex

Note that this is also achievable without regex.

text = 'this is a test'
match = [word for word in text.split() if not word.startswith('t')]

print(match) # prints: ['is', 'a']


from : https://stackoverflow.com/questions/50374496/match-words-that-dont-start-with-a-certain-letter-using-regex

No comments:

Post a Comment