-1

I'm trying to use a JavaScript regular expression to check a string for anything that matches a certain set of letters followed by either 5 or 6 numbers. For example, if the string is 'MyValue12345 blah blah MyValue123456 blah MyValue222221', it should return a match of ['MyValue12345', 'MyValue123456', 'MyValue222221']. I'm a RegEx novice (clearly), and my expression gets close but not exactly what I'm looking for...

Here is my first try:

var str = 'MyValue12345 blah blah MyValue123456 blah MyValue222221';
var matchArr = str.match(/MyValue\d\d\d\d\d|MyValue\d\d\d\d\d\d/gi);

matchArr then equates to ['MyValue12345', 'MyValue123456', 'MyValue22222'], but the last value of MyValue22222 isn't what I'm looking for, I want it to say the full expression of MyValue222221. I know there's a better way to do this but I'm struggling to get it...any thoughts?

brianyates
  • 399
  • 3
  • 16

2 Answers2

1

Use a quantifier range {n,m} (regex101):

var str = 'MyValue12345 blah blah MyValue123456 blah MyValue222221';
var matchArr = str.match(/MyValue\d{5,6}/gi);

console.log(matchArr);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

The regex tries to apply the first pattern of your | alternative, and when that matches that's the result. Only when it doesn't match, it will try the second alternative. So you would swap the two to make it work:

/MyValue\d\d\d\d\d\d|MyValue\d\d\d\d\d/gi

However, that's quite repetitive - better use a group around the difference:

/MyValue\d\d\d\d\d(?:\d|)/gi
//                ^^^^^^^ one digit or none

You can shorten that syntactically with a ? modifier that will match "one or nothing":

/MyValue\d\d\d\d\d\d?/gi
//                ^^^ one digit or none

Last but not least you'll want to have a look at repetition syntax:

/MyValue\d{5}\d?/gi
//      ^^^^^ five digits
/MyValue\d{5,6}/gi
//      ^^^^^ five or six digits
Bergi
  • 630,263
  • 148
  • 957
  • 1,375