开发者

Regex to select parenthesis

开发者 https://www.devze.com 2023-03-13 21:20 出处:网络
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 el

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消