-1

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}
Dale K
  • 25,246
  • 15
  • 42
  • 71

2 Answers2

1

You want to use

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

Details

  • ^ - start of a string
  • [A-Z ]{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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

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 = /^[A-Z ]{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:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69