Reputation: 1233
Working on a regex pattern to sanitize HTML output and remove any special characters. My thought is to write a regex listing all the characters I want to keep and remove everything else rather then trying to account for all special characters in the pattern.
My current pattern:
/[^0-9A-Za-z,=": ?'`&;>|<!.\-\/]/
It's working great, except it is removing parenthesis () which I'd like to keep. I can't seem to escape them correctly when adding to my pattern. What is the best way to do this?
Upvotes: 0
Views: 206
Reputation: 80065
str.delete( %q{^a-zA-Z1-9,=:"`&;>|<!.-/ ()'} )
# or with another delimiter (*):
str.delete( %q*^a-zA-Z1-9,=:"`&;>|<!.-/ ()'* )
String.delete takes one or more strings as argument (and negates them with '^', just like a regex). With the %q{string} syntax you don have to worry about escaping.
Upvotes: 0
Reputation: 37517
The best way is to use the sanitize method built in to Rails.
Upvotes: 2
Reputation: 2605
/[^0-9A-Za-z,=": ?'`&;>|<!.\-\/()]/
Inside range blocks "[]", different escape rules apply.
Upvotes: 4