Ruby on rails 避免使用一组字符的正则表达式
我使用的是RubyonRails 3.1.0,我想验证一个类属性,以避免在数据库中存储一个包含以下字符的字符串:Ruby on rails 避免使用一组字符的正则表达式,ruby-on-rails,ruby,regex,string,validation,Ruby On Rails,Ruby,Regex,String,Validation,我使用的是RubyonRails 3.1.0,我想验证一个类属性,以避免在数据库中存储一个包含以下字符的字符串:(空白)、,“,,%,{/code>,”,,\,^,~,[,]和``````` 什么是正则表达式?假设它也应该是非空的: ^[^\] ><"#%{}|\\^~\[`]+$ a=“foobar” b=“foo`bar” re=/[\^”\\\\\\\\\\\\[\]\`]/ a=~re#=>零 b=~re#=>3 逆表达式为: /\A[^ \^<>"#%\{\
(空白)、
,“
,,%
,{/code>,”
,
,\
,^
,~
,[
,]
和```````
什么是正则表达式?假设它也应该是非空的:
^[^\] ><"#%{}|\\^~\[`]+$
a=“foobar”
b=“foo`bar”
re=/[\^”\\\\\\\\\\\\[\]\`]/
a=~re#=>零
b=~re#=>3
逆表达式为:
/\A[^ \^<>"#%\{\}\|\\~\[\]\`]+\Z/
/\A[^\^”\\%\{\\\\\\\~\[\]\`]+\Z/
坏字符=%w(<>“{}{}\^~[]))
re=Regexp.union(坏字符)
p%q(hoh'oho)=~re#=>3
Regexp.union
负责转义。@Octopus Paul:the]
将结束字符类,而\s
序列在字符类中不起作用。@Porges\s
在字符类中工作正常。除了上面的“b”之外?正则表达式为坏字符串返回一个真实值,为好字符串返回一个nil
,因此您需要反转逻辑。请注意,有一种=~
的反转可用,即~代码>。像b!~re#=>false
。我需要在RubyonRails中使用正则表达式来验证
方法的格式。那么,我怎样才能正确地使用您的正则表达式来实现我想要实现的目标呢?@user502052/\A[^\^”\\\\\\\\\\\~[]+\Z/编辑了答案,因为由于反勾,我无法在注释中格式化模式。
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
nil
0
a = "foobar"
b = "foo ` bar"
re = /[ \^<>"#%\{\}\|\\~\[\]\`]/
a =~ re # => nil
b =~ re # => 3
/\A[^ \^<>"#%\{\}\|\\~\[\]\`]+\Z/
bad_chars = %w(< > " # % { } | \ ^ ~ [ ] ')
re = Regexp.union(bad_chars)
p %q(hoh'oho) =~ re #=> 3