user2918984
user2918984

Reputation: 121

Regex, replace all underscore and special char with spaces?

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

Answers (4)

user2918984
user2918984

Reputation: 121

I got it, changed it to:

    new_str = re.sub(r'[\w_+]', ' ', new_str)

Upvotes: 0

Tim Pierce
Tim Pierce

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

gongzhitaao
gongzhitaao

Reputation: 6682

new_str = re.sub(r'[^\w]|_', ' ', new_str)

Upvotes: 0

Martijn Pieters
Martijn Pieters

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

Related Questions