使用正则表达式验证用户输入的版本号

时间:2013-10-07 12:01:39

标签: ruby validation version

我需要在用户输入时验证版本号,例如6.0.2 / 6.0.2.011。 我检查了to_i,但它不符合我的目的。有什么方法可以验证版本号?谁能让我知道?

3 个答案:

答案 0 :(得分:2)

这是一个正则表达式,根据您的规范匹配“有效”版本号(仅由.分隔的数字):

/\A\d+(?:\.\d+)*\z/

此表达式可以分解如下:

\A        anchor the expression to the start of the string
\d+       match one or more digit character ([0-9])
(?:       begin a non-capturing group
  \.      match a literal dot (.) character
  \d+     match one or more digit character
)*        end the group, and allow it to repeat 0 or more times
\z        anchor the expression to the end of the string

此表达式仅允许.后跟至少一个以上的数字,但会允许版本号的任意数量的“部分”(即。66.06.0.26.0.2.011都匹配)。

答案 1 :(得分:0)

如果您想使用版本号,我建议versionomyGithub)gem。

答案 2 :(得分:0)

看看这是否有帮助。

if a.length == a.scan(/\d|\./).length
  # only dots and numbers are present
  # do something
else
  # do something else
end

e.g

a = '6.0.2.011' 
a.length == a.scan(/\d|\./).length #=> true

b = '6b.0.2+2.011'
b.length == b.scan(/\d|\./).length #=> false

根据扫描结果的长度检查输入长度,以确保只存在点和数字。话虽如此,很难保证未来的版本号都遵循相同的约定。你如何确保某些人不会介绍6a.0.2.011

之类的内容