简体   繁体   中英

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:

在此输入图像描述

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?

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

Try this regex:

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

RegEx Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM