简体   繁体   English

Ruby Regexp完全匹配字符串

[英]Ruby Regexp Match String Exactly

I've a Ruby regexp question. 我有一个Ruby正则表达式问题。

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

I want the regexp to match only "24". 我希望正则表达式只匹配“24”。
How should I do to only allow digits? 我该怎么做只允许数字?

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

Incidentally, if you only want to match "24" (not "39" or "42") you don't want a regex, you want to do a direct comparison: 顺便提一下,如果你只想匹配“24”(不是“39”或“42”)你不想要一个正则表达式,你想要做一个直接的比较:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM