Harrison Harrison - 1 year ago 321
Python Question

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

I currently have this line

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

Answer Source

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


See the regex demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download