bevanb
bevanb

Reputation: 8511

Ruby regex: replace non-word chars that are not space chars

How do I replace all non-word chars (\W) that are also not space characters (\s)?

This is the desired functionality:

"the (quick)! brown \n fox".gsub(regex, "#")

=>

"the #quick## brown \n fox"

Upvotes: 21

Views: 15869

Answers (2)

Robbie
Robbie

Reputation: 19500

I think you need a regex like this one:

/[^\w\s]/

When you add a circumflex ^ to the start of a character set, it negates the expression so that anything except characters in the set are matched.

Upvotes: 11

Chris Zelenak
Chris Zelenak

Reputation: 2178

"the (quick)! brown \n fox".gsub(/[^\w\s]/, "#")

By making the regex replace anything that is NOT a word character OR a space character.

Upvotes: 31

Related Questions