user502052
user502052

Reputation: 15258

Regular expression to avoid a set of characters

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

Answers (3)

porges
porges

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

d11wtq
d11wtq

Reputation: 35318

a = "foobar"
b = "foo ` bar"

re = /[ \^<>"#%\{\}\|\\~\[\]\`]/

a =~ re # => nil
b =~ re # => 3

The inverse expression is:

/\A[^ \^<>"#%\{\}\|\\~\[\]\`]+\Z/

Upvotes: 2

steenslag
steenslag

Reputation: 80105

bad_chars = %w(< > " # % { } | \ ^ ~ [ ] ')
re = Regexp.union(bad_chars)
p %q(hoh'oho) =~ re #=> 3

Regexp.union takes care of escaping.

Upvotes: 2

Related Questions