gpt4 book ai didi

ruby - 匹配数字格式的正则表达式

转载 作者:数据小太阳 更新时间:2023-10-29 08:51:02 25 4
gpt4 key购买 nike

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

我的问题是应该使用什么正则表达式来防止像“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

最佳答案

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

这是超紧凑的版本

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

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

关于ruby - 匹配数字格式的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12883086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com