Quentin Manfroi
Quentin Manfroi

Reputation: 387

Python regex to remove all words which contains number

I am trying to make a Python regex which allows me to remove all worlds of a string containing a number.

For example:

in = "ABCD abcd AB55 55CD A55D 5555"
out = "ABCD abcd"

The regex for delete number is trivial:

print(re.sub(r'[1-9]','','Paris a55a b55 55c 555 aaa'))

But I don't know how to delete the entire word and not just the number.

Could you help me please?

Upvotes: 21

Views: 21969

Answers (3)

SACHIN GIRI
SACHIN GIRI

Reputation: 11

The below code of snippet removes the words mixed with digits only

string='1i am20 years old, weight is in between 65-70 kg  '

string=re.sub(r"[A-Za-z]+\d+|\d+[A-Za-z]+",'',string).strip()

print(s)

OUTPUT: years old and weight is in between 65-70 kg name

Upvotes: 1

user2555451
user2555451

Reputation:

Here's my approach:

>>> import re
>>> s = "ABCD abcd AB55 55CD A55D 5555"
>>> re.sub("\S*\d\S*", "", s).strip()
'ABCD abcd'
>>>

Upvotes: 14

arshajii
arshajii

Reputation: 129507

Do you need a regex? You can do something like

>>> words = "ABCD abcd AB55 55CD A55D 5555"
>>> ' '.join(s for s in words.split() if not any(c.isdigit() for c in s))
'ABCD abcd'

If you really want to use regex, you can try \w*\d\w*:

>>> re.sub(r'\w*\d\w*', '', words).strip()
'ABCD abcd'

Upvotes: 32

Related Questions