Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 避免使用一组字符的正则表达式_Ruby On Rails_Ruby_Regex_String_Validation - Fatal编程技术网

Ruby on rails 避免使用一组字符的正则表达式

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[^ \^<>"#%\{\

我使用的是RubyonRails 3.1.0,我想验证一个类属性,以避免在数据库中存储一个包含以下字符的字符串:
(空白)、
%
{/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