Ruby正则表达式:精确匹配字符串

5

我有一个关于Ruby正则表达式的问题。

if string == /(^\d{1,3})/ # this matches both "24" and "24 gravida ut aliquam"
  # code...
end

我希望正则表达式只匹配"24"这个数字。
应该怎么做才能只允许数字?

1个回答

10
if string =~ /(^\d{1,3}$)/
  # code...
end

顺便提一句,如果你只想匹配"24"(而不是"39"或"42"),你不需要使用正则表达式,你需要进行直接比较:

if string == "24"
  # code...
end

非常感谢,回复非常迅速!=) - axeljohnsson
我想匹配所有的数字,最多到999。/(^\d{1,3}$)/非常有效,谢谢。 - axeljohnsson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接