adviner
adviner

Reputation: 3567

Regular expression not matching string

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?

Upvotes: 1

Views: 56

Answers (1)

anubhava
anubhava

Reputation: 786091

  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

Upvotes: 3

Related Questions