Regex to select parenthesis
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 r开发者_如何学编程emove 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?
/[^0-9A-Za-z,=": ?'`&;>|<!.\-\/()]/
Inside range blocks "[]", different escape rules apply.
The best way is to use the sanitize method built in to Rails.
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.
精彩评论