1

Any Regex gurus out there? I have a position_id that is a string and can have the following formats. The number of digits can very, but is sort-of like so. all digits or digits and one dash '-'.

123456  or
123456-123

I need a regular expression that says, if position_id is not in that/those formats, throw a flag. I thought I had it with the following, but it doesn't seem to work. maybe my syntax is wrong.

if !params[:position_id] =~ /^\d+-?\d+$/
  flash[:error] = "error message here"
end

any help would be appreciated.

2 Answers 2

1

It should work as long as you have at least 2 digits numbers. I guess you're testing it with 1 digits one?

If so, this should do it :

flash[:error] = "error message here" unless params[:position_id] =~ /^\d+(-\d+)?$/

We're making the whole -123 optional there

Sign up to request clarification or add additional context in comments.

4 Comments

actually, I'm testing with asdfsadfdsaf just to see if I can any error message back. Users should not be able to enter any non-digit characters other than the '-'. Should be just digits and maybe one dash.
generally speaking hyphens should be escaped
Hmmm all of the answers given work in the console. just not my controller. Grrrr! Thanks for the help though
Then I'd log somewhere params[:position_id] to see if it's actually what you think it is!
0

Here is a simple one:

^([0-9]*)(\-[0-9]*)?$

http://rubular.com/r/2qSTHIPEo9

If you expect the number range to be a certain length just change it up as so:

^([0-9]{6})(\-[0-9]{3,4})?$

which says in words:

  • "any number thats 6 digits long"
  • "if there is a hyphen the second number must be between 3 and 4 digits"

http://rubular.com/r/5SHiJ1GKiK

EDIT: -- to answer the comment below

if !params[:position_id].match(/^([0-9]{6})(\-[0-9]{3,4})?$/)
    flash[:error] = "not valid"
end

http://ruby-doc.org/core-2.0/String.html#method-i-match

1 Comment

I changed the code to just /\d/ and it won't catch on that with no digits. I test for params[:position_id].blank? so I know I have the param showing. Never had so much trouble on an easy regex.

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.