正则表达式匹配数字格式

时间:2012-10-14 14:20:30

标签: ruby regex

我正在尝试编写一个小程序,要求用户输入一个数字,程序将确定它是否是有效数字。用户可以输入任何类型的数字(整数,浮点数,科学记数法等)。

我的问题是应该使用正则表达式来保持“7w”之类的匹配作为有效数字吗?此外,我希望数字0退出循环并结束程序,但正如现在写的那样0匹配有效,就像任何其他数字一样。有什么见解吗?

x = 1

while x != 0
  puts "Enter a string"
  num = gets

  if num.match(/\d+/)
    puts "Valid"
  else
    puts "invalid"
  end

  if num == 0
    puts "End of program"
    x = num
  end   
end

2 个答案:

答案 0 :(得分:2)

您需要从命令行执行此脚本,而不是文本编辑器,因为您将提示输入数字。

这是超紧凑版

def validate(n)
  if (Float(n) != nil rescue return :invalid)
    return :zero if n.to_f == 0
    return :valid
  end
end
print "Please enter a number: "
puts "#{num = gets.strip} is #{validate(num)}"

输出:

Please enter a number: 00
00 is zero

这是一个较长的版本,您可以扩展它以根据您的需要进行调整。

class String
  def numeric?
    Float(self) != nil rescue false
  end
end

def validate(n)
  if n.numeric?
    return :zero if n.to_f == 0
    return :valid
  else
    return :invalid
  end
end

print "Please enter a number: "
puts "#{num = gets.strip} is #{validate(num)}"

这是对所有可能情况的测试

test_cases = [
  "33", #int pos
  "+33", #int pos
  "-33", #int neg
  "1.22", #float pos
  "-1.22", #float neg
  "10e5", #scientific notation
  "X", #STRING not numeric
  "", #empty string
  "0", #zero
  "+0", #zero
  "-0", #zero
  "0.00000", #zero
  "+0.00000", #zero
  "-0.00000", #zero
  "-999999999999999999999995444444444444444444444444444444444444434567890.99", #big num
  "-1.2.3", #version number
  "  9  ", #trailing spaces
]

puts "\n** Test cases **"
test_cases.each do |n|
  puts "#{n} is #{validate(n)}"
end

哪个输出:

Please enter a number: 12.34
12.34 is valid

** Test cases ** 33 is valid
+33 is valid
-33 is valid
1.22 is valid
-1.22 is valid
10e5 is valid
X is invalid
 is invalid
0 is zero
+0 is zero
-0 is zero
0.00000 is zero
+0.00000 is zero
-0.00000 is zero
-999999999999999999999995444444444444444444444444444444444444434567890.99 is valid
-1.2.3 is invalid
   9   is valid

检查是否有数字的想法的来源:

答案 1 :(得分:1)

首先,你使循环过于复杂,其次,你的正则表达式需要更明确一些。尝试这样的事情:

x = 1

while x != 0
  puts "Enter a string"
  num = gets.chomp
  if num == "0"
    puts "exiting with 0"
    exit 0
  elsif num.match(/^[0-9](\.[0-9])?$+/)
    puts "Valid"
  else
    puts "invalid"
  end
end

此表达式将匹配包含数字或小数的任何数字,并且无法匹配包含字母的任何内容。如果输入的字符串正好为0,则脚本将以状态0退出。