Home > front end >  How to remove or mimic the negative lookbehind?
How to remove or mimic the negative lookbehind?

Time:03-04

Please do not close the question. I have already gone through Negative lookbehind equivalent in JavaScript, javascript regex - look behind alternative? but I am unable to get the correct regex. I have really tried myself, but not successful. I have did multiple trials to get the answer. As was unsuccessful hence posted this question.

I have a regular expression. It is working perfectly fine in the Chrome browser, but I face an issue in Safari and IOS. The issue is the negative lookbehind. Is there a way to either remove or mimic the negative lookbehind, so that the same expressions can work in all 3 environments?

const regex = /(?<!\[)@([\w.'-] (?:\s[\w.'-] )?)/g;

I am using the above regex to perform the below function. The string data is dynamically received from a textarea.

Is there any other way to get the desired result without regex?

const stringData = "[@Shilpa Shetty] [@Rohit Shetty] [@Rohit Bahl] @Salman Khan [@Sonal Shetty][@Mary James], [@Jennifer John] and [@Johnny Lever[@Patricia Robert] are present in the meeting and [@Jerry[@Jeffery Roger] is absent.";

while ((match = regex2.exec(stringData)) !== null) {
   console.log('Starting Index', match.index);
   console.log('Ending Index', regex2.lastIndex);
}

I have attached two demos.

This one is to be opened in chrome and tested => https://regex101.com/r/DUbiiK/1

This one is to be opened in safari and tested => https://regexr.com/6gl48

Need help as regular expressions is something very new for me, and I have tried multiple times, but am unable to get the desired result.

CodePudding user response:

I would go for something like this:

/(?:^|[^\[])@([\w.'-] (?:\s[\w.'-] )?)/g
  • (?:^|[^\[]) - lead with either the start of a line or non-[ char
  • @([\w.'-] (?:\s[\w.'-] )?) - unchanged. I assume you know what you wrote...

const regex = /(?:^|[^\[])@([\w.'-] (?:\s[\w.'-] )?)/g;

const stringData = "@Salman Khan [@Shilpa Shetty] [@Rohit Shetty] [@Rohit Bahl] @Salman Khan [@Sonal Shetty][@Mary James], [@Jennifer John] and [@Johnny Lever[@Patricia Robert] are present in the meeting and [@Jerry[@Jeffery Roger] is absent.";

while ((match = regex.exec(stringData)) !== null) {
    
    // If we've matched something at the start of the line then don't compensate for the superfluous char before @
    // If something was matched in the middle of the string then compensate  for whatever preceded the `@`
    console.log('Starting Index', (match.index < 1 ? match.index : (match.index   1)));
    console.log('Ending Index', regex.lastIndex);
}

  • Related