使用正则表达式验证以逗号分隔的单词字符串的格式 [英] Validate the format of a string of comma separated words with regex
问题描述
我正在尝试使用正则表达式从ruby类的文本字段中验证由逗号分隔的单词的字符串.以下内容应有效:
I'm trying to validate a string of comma separated words from a text field in a ruby class using regex. The following should be valid:
word
word, word, word
word,word,word
以下内容无效:
word word word
我认为这会起作用
/([a-z]+){1}(,\s*[a-z]+)*/i
在Rubular上,它似乎是有效的,但是当我按如下所示在类中进行验证时,它接受应该是无效的字符串.
On Rubular, it seems to be valid, but when I validate in my class as follows, it accepts what should be invalid strings.
@tag_regex = /([a-z]+){1}(,\s*[a-z]+)*/i
validates :tags,
:allow_blank => true,
:format => { :with => @tag_regex, :message => "Invalid tag format." }
我不确定我的问题出在正则表达式还是验证方法本身.感谢您的帮助.
I'm not sure whether my problem lies in the regex or with the method of validation itself. Any help is appreciated.
推荐答案
您忘记使用^
(字符串的开头)和$
(字符串的结尾)
You forgot to use ^
(start of the string) and $
(end of the string)
所以应该是
/^([a-z]+)(,\s*[a-z]+)*$/i
如果没有^
,$
,它将在字符串之间的任意位置匹配.使用^
,$
,您将使其完全匹配
Without ^
,$
it would match anywhere in between the string..With ^
,$
you are making it match exactly
这篇关于使用正则表达式验证以逗号分隔的单词字符串的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!