Python regular expression to remove all words containing a number

I am trying to create a Python regex that allows me to delete all the worlds of a string containing a number.

For instance:

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

The regular expression for the delete number is trivial:

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

But I do not know how to delete the whole word, not just a number.

could you help me?

+6
source share
2 answers

Do you need 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' 
+14
source

Here is my approach:

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

Source: https://habr.com/ru/post/951135/


All Articles