Flake
Flake

Reputation: 4497

Match a term ending with digit

I have a list of words, with patterns either "term" or "termNUM", e.g. "term" or "term02". I want to save all terms that ends with digit but remove the ones are purely alphabets.

I am totally new to regex, I tried few options, and get the following:

new_list = [x for x in old_list if re.match("[(^a-zA-Z_)\d]", x)]

It is not working, I know it only need a small tweak somewhere, but with my limited skill in regex, cannot do it quickly.

Tips are highly appreciated.

Upvotes: 0

Views: 119

Answers (3)

Fred Foo
Fred Foo

Reputation: 363527

r".*\d"

That's any character (.), any number of times (*) followed by a digit (\d). Your list comprehension is correct.

You could also do

[x for x in old_list if x[-1].isdigit()]

assuming the empty string is not in the list. I'd prefer this option, as it's more explicit as to what it does.

Upvotes: 3

Avaris
Avaris

Reputation: 36715

Why use regex, where you can simply check the last char is a digit or not. i.e.

new_list = [x for x in old_list if x[-1].isdigit()]

Upvotes: 3

Dogbert
Dogbert

Reputation: 222108

>>> list = ["term", "term2", "term200"]
>>> new_list = [x for x in list if re.match("^[a-zA-Z_]+\d+$", x)]
>>> new_list
['term2', 'term200']

Upvotes: 2

Related Questions