Reputation: 121
so im trying to replace all special chars into spaces, using regex: my code works, but it wont replace underscore, what should i do?
code:
new_str = re.sub(r'[^\w]', ' ', new_str)
its working on all of the other special chars but not underscore.
Upvotes: 2
Views: 6642
Reputation: 121
I got it, changed it to:
new_str = re.sub(r'[\w_+]', ' ', new_str)
Upvotes: 0
Reputation: 5664
Underscore is considered a "word character" in PCRE regular expressions. If what you want to match is "anything that is not a word character or an underscore", try this:
new_str = re.sub(r'[\W_]', ' ', new_str)
Upvotes: 6
Reputation: 1122132
The underscore is part of the \w
character group. Use this instead:
new_str = re.sub(r'[^a-zA-Z0-9]', ' ', new_str)
which is the same as \w
but minus the underscore.
Upvotes: 0