简体   繁体   中英

RegEx for matching an alphanumeric pattern with quantifier

I am trying to limit the digits between 4 and 6 in my regex but it is not working

Minimum range works but the max range does not work:

  • Some Text-1 = validates
  • Some Text-201901 = validates
  • Some Text-20190101 = passes the validation where it should fail

Now if I add $ at the end then none of the above work.

Code:

^[A-Z ]{3,}-\d{4,6}

You want to use

^[A-Z ]{3,}-[0-9]{3,6}(?!\d)

Details

  • ^ - start of a string
  • [AZ ]{3,} - three or more uppercase letters or spaces
  • - - a hyphen
  • [0-9]{3,6} - three to six digits
  • (?!\\d) - a negative lookahead that fails the match if, immediately to the right of the current location, there is a digit.

I'm not quite sure, what we might wish to pass and fail, however based on your original expression my guess is that this might be what we might want to start with with an i flag:

^[A-Z ]{3,}-\d{1,6}$

or without i flag:

^[A-Za-z ]{3,}-\d{1,6}$

Demo

Test

 const regex = /^[AZ ]{3,}-\\d{1,6}$/gmi; const str = `Some Text-1 Some Text-201901 Some Text-20190101`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); } 

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com .

RegEx Circuit

jex.im visualizes regular expressions:

在此处输入图片说明

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