1

I'm trying to figure out the following regular expression:

/^[0-9]{2}-[0-9]{2,3}[a-zA-z]{0,1}/g

In my example.
The following should pass: 00-45, 00-333, 33-333a, 55-34a The following should fail: 33-3333, 22-22dd, 22-2233

Here is my screenshot:

enter image description here

But the once that should fail arent failing. In my javascript code I just do a test:

var regExp = new RegExp(exp);
if(regExp.test(test1))
    alert('pass');
else
    alert('fail');

Is there a way for the regular expression to test the entire string? Example 33-3333 passes because of 33-333, but since there is another 3 I would like it to fail since the fourth 3 would be tested against the character rule?

2
  • use ^ and $ to indicate line beginning and ending Commented May 6, 2016 at 17:30
  • Did you forget glob? - new RegExp(exp, 'g'); ? Commented May 6, 2016 at 17:31

1 Answer 1

3
  1. You are missing end anchor $ in your input
  2. A-z inside character class will match unwanted characters as well, you actually need A-Z
  3. {0,1} can be shortened to ?

Try this regex:

/^[0-9]{2}-[0-9]{2,3}[a-zA-Z]?$/

RegEx Demo

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

2 Comments

You are so speed. :)
Thanks all, it seems like I forgot the $. I do like your shorter version of removing the last {0,1} for just ?

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.