我完全是正则表达式的菜鸟。对于 Ruby on Rails 项目,我需要一个字段来允许所有字母但禁止双引号。知道如何制定吗?
非常感谢
只需使用否定字符类:
[^"]
字符类将包含除双引号之外的所有字符。如果你想用你可能想要的验证一个字符串
^[^"]*$
匹配字符串。
如果您想使用格式验证助手:
validates :your_field, format => {
:with => /\A[^"]+\z/,
:message => "No quotes allowed"
}
正则表达式:
\A
从字符串的开头
[^"]
允许任何字符,除了"
+
一次或多次
\z
到字符串的末尾
你可以使用:
if subject =~ /\b[[:alpha:]]+\b/i
# Successful match
else
# Match attempt failed
end
解释
"
\\b # Assert position at a word boundary
[[:alpha:]] # Match a single character present in the list below
# A character in the POSIX character class “alpha”
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\\b # Assert position at a word boundary
"
您需要指定从开始到结束的每个字符都不能是 "
:
^[^"]*$
这意味着:
^
:匹配必须从行或字符串的开头开始;: 匹配除;
[^"]
以外的任何字符(字母、标点符号、...):匹配上一项零次或多次;: 匹配必须在行或字符串的末尾结束。"
*
$