Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Regexp Match String Exactly

Tags:

regex

ruby

I've a Ruby regexp question.

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

I want the regexp to match only "24".
How should I do to only allow digits?

like image 633
axeljohnsson Avatar asked Dec 28 '22 08:12

axeljohnsson


1 Answers

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:

if string == "24"
  # code...
end
like image 188
Dominic Rodger Avatar answered Feb 11 '23 22:02

Dominic Rodger