5

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?

1 Answer 1

10
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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, very fast reply! =)
I want to match all digits up to 999. /(^\d{1,3}$)/ works great, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.