I've been wrestling with this for a while and can't figure it out. I see in Regex to match string containing two names in any order that lookarounds can be used to look for words occurring in any order. I added some additional groups to the example from that post:
const regex = /^(?=.*\b(jack)\b)(?=.*\b(james)\b).*$/;
"hi james this is jack".match(regex);
// => ["hi james this is jack", "jack", "james"]
However, I also want to make both of the words optional. That is, something like this:
"hi james this is jack".match(someMagicRegex);
// => ["hi james this is jack", "jack", "james"]
"hi this is jack".match(someMagicRegex);
// => ["hi this is jack", "jack", undefined]
"hi james".match(someMagicRegex);
// => ["hi james", undefined, "james"]
The important thing would be that the matches remain in the correct order. That is the jack
match would always be the second element in the matches array.
I've tried adding ?
at different places (including after new groupings), but nothing I tried produced the desired result.
Is something like this possible?
UPDATE: To be more specific, I'm going to be using this on a series of CSS media queries and am looking to match optional min-width: Xpx
and max-width: Ypx
expressions:
"only screen and (min-width: 500px) and (max-width: 599px)".match(someMagicRegex);
// => ["...", "500", "599"]
"only screen and (min-width: 500px)".match(someMagicRegex);
// => ["...", "500", undefined]
"(max-width: 599px)".match(someMagicRegex);
// => ["...", undefined, "599"]
(Where the second match would be the numeric portion of the min-width value and the third match would be the numeric portion of the max-width value.)