Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all non-alphanumeric characters from a string, except for '#', with regex?

Tags:

python

regex

I currently have this line address = re.sub('[^A-Za-z0-9]+', ' ', address).lstrip() which will remove all special characters from my string address. How can I modify this line to keep #?

like image 970
Harrison Avatar asked Aug 08 '16 15:08

Harrison


1 Answers

In order to avoid removing the hash symbol, you need to add it into the negated character class:

r'[^A-Za-z0-9#]+'
             ^

See the regex demo

like image 65
Wiktor Stribiżew Avatar answered Nov 08 '22 20:11

Wiktor Stribiżew