0

I'm looking to have a regex that validates any string from 046R to 120R.

Sounds simple enough, but I'm missing something here. this is what I have:

^04[6-9]R|0[5-9][0-9]R|10[0-9]R|11[0-9]R|120R +$

But it's not picking up the 120R as a valid string as well. As can this expression be simplified?

Thanks in advance.

2
  • 2
    Why do you have ` +` (only) after 120R? It means that when you have 120R, it has to be followed by at least one space. Commented Apr 3, 2011 at 21:13
  • 10[0-9]R|11[0-9]R ~ 1[01][0-9]R. Commented Apr 3, 2011 at 21:16

2 Answers 2

2

Remove the final  +. Otherwise it requires one or more space after the string 120R to be validated.

Also, | has very low precedence. The ^ and $ should stay outside of the group containing |.

^(?:04[6-9]|0[5-9][0-9]|1[01][0-9]|120)R\s*$
Sign up to request clarification or add additional context in comments.

3 Comments

Beat me to it. One more thing, though - if you do want to allow trailing spaces, you can use * (zero or more) instead of + (one or more): ^(...)R *$ Cheers!
That's not working out. It doesn't accept some of the values that it should. Have a look: [link]rubular.com/r/YZsPIRInNV
@Bruno: That's because your test case is not "clean" — some entries contains unnecessary trailing space. This can be fixed by adding a \s* at the end like Xavier's comment. See rubular.com/r/3prIDsOncr
1

You can exclude certain matches by using negative lookahead, and simplify the regex.

^(?!0[0-3])(?!04[0-5])[01]\d\dR$

Comments

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.