Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insure that regex moves to the second OR element only if the first one doesn't exist

I'm trying to match a certain word on a string and only if it doesn't exist i want to match the another one using the OR | operator ....but the match is ignoring that... how can i insure that the behavior works :

const str = 'Soraka is an ambulance 911'
const regex = RegExp('('+'911'+'|'+'soraka'+')','i')
console.log(str.match(regex)[0])     // should get 911 instead
like image 365
user121548789 Avatar asked Dec 14 '25 18:12

user121548789


1 Answers

911 occurs late in the string, whereas Soraka occurs earlier, and the regex engine iterates character-by-character, so Soraka gets matched first, even though it's on the right-hand side of the alternation.

One option would be to match Soraka or 911 in captured lookaheads instead, and then with the regex match object, alternate between the two groups to get the one which is not undefined:

const check = (str) => {
  const regex = /^(?=.*(911)|.*(Soraka))/;
  const match = str.match(regex);
  console.log(match[1] || match[2]);
};

check('Soraka is an ambulance 911');
check('foo 911');
check('foo Soraka');
like image 178
CertainPerformance Avatar answered Dec 17 '25 09:12

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!