Harrison
Harrison

Reputation: 5396

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 address. How can I modify this line to keep #?

Upvotes: 5

Views: 6709

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

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

Upvotes: 6

Related Questions