>>> import re
>>> words = ["hello", "18hs", "18aaa", "21hr"]
>>> [w for w in words if not re.match(r'\d+h', w)]
['hello', '18aaa']
This loops over the list and keeps the items that don’t match the regex \d+h
, which means “one or more digits followed by an h”.
If you need to keep strings like 7hg
, use a more specific regex, \d+h(s|r)?$
, which means “one or more digits, h, optional s or r, end of string”:
>>> words = ["hello", "18hs", "18aaa", "21hr", '7hg']
>>> [w for w in words if not re.match(r'\d+h(s|r)?$', w)]
['hello', '18aaa', '7hg']
Also note that re.match
automatically matches the start of the string, so it’s like an implicit ^
at the start of the regex.
3
solved How do I remove all strings containing digits before “hs” like “18hs” from a list of strings? [closed]