-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?

3
  • I'm getting ["MyValue12345", "MyValue12345", "MyValue22222"] Commented Sep 19, 2018 at 19:04
  • Yeah I think I had some typos; I've since made some edits...but basically I want the last element to be MyValue222221 rather than MyValue22222. Commented Sep 19, 2018 at 19:05
  • You could use + to make the selection greedy? MyValue\d+? Commented Sep 19, 2018 at 19:05

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.