GBR24 GBR24 - 3 months ago 13
Python Question

regex to remove ANY number/letter combination?

It's easy to remove all digits from the following

string
:

>>> string = "asprx12303 hello my 321 name is Tom 2323dsad843, 657a b879 843aa943 aa... 2ci 2ci"
>>> modified = re.sub(r'\d+', '', string)
>>> print(modified)
'asprx hello my name is Tom dsad, a b aa aa... ci ci'


But I want to remove every standalone digit (e.g.
321
by itself) and every combination of letters and numbers in the string (e.g.
843aa943
and
asprx12303
).

This is what I have so far:

>>> modified2 = re.sub(r'\w+\d+', '', string)
>>> print(modified2)
' hello my name is Tom , a aa... 2ci 2ci'


So, these two patterns work pretty well, but I'm left with
2ci
at the end. How can I make an all-encompassing regex for this issue? My solution is ok so far, but is not quite what I need.

Answer

Something like this:

r'\w*[0-9]\w*'

That should match any contiguous run of word characters containing at least one digit.

Comments