Reputation: 15258
I am using Ruby on Rails 3.1.0 and I would like to validate a class attribute just to avoid to store in the database a string containing these characters: (blank space),
<
, >
, "
, #
, %
, {
, }
, |
, \
, ^
, ~
, [
, ]
and ```.
What is the regex?
Upvotes: 0
Views: 505
Reputation: 30590
Assuming it should also be non-empty:
^[^\] ><"#%{}|\\^~\[`]+$
Since someone is downvoting this, here is some test code:
ary = [' ', '<', '>', '"', '#', '%', '{', '}', '|', '\\', '^', '~', '[', ']', '`', 'a']
ary.each do |i|
puts i =~ /^[^\] ><"#%{}|\\^~\[`]+$/
end
Output:
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
0
Upvotes: 3
Reputation: 35318
a = "foobar"
b = "foo ` bar"
re = /[ \^<>"#%\{\}\|\\~\[\]\`]/
a =~ re # => nil
b =~ re # => 3
The inverse expression is:
/\A[^ \^<>"#%\{\}\|\\~\[\]\`]+\Z/
Upvotes: 2
Reputation: 80105
bad_chars = %w(< > " # % { } | \ ^ ~ [ ] ')
re = Regexp.union(bad_chars)
p %q(hoh'oho) =~ re #=> 3
Regexp.union
takes care of escaping.
Upvotes: 2