Home > Net >  Regex to match a string which does NOT have some words before @ symbol
Regex to match a string which does NOT have some words before @ symbol

Time:04-19

I want to discard a string if some words are present before the character @ in it.

Example: I want words foo and bar that should NOT be present on a string before @ symbol but the same words are allowed after @ symbol.

I do NOT want these:

abcfoo[email protected]

bar[email protected]

barabc@domainfoo.com

I want these:

abcxyz@domainfoo.com

pqrabc@domainbar.com

[email protected]


I have regex ^((?!(foo|bar)).)*$, but it also discards strings that have foo and bar after @ symbol even if the words are NOt present before @.

I only want it to discard if foo or bar is present before @ symbol in a string.


Do you have an idea how can I do it? Thanks.

CodePudding user response:

You need to assert at each character position preceding the @ that it is not the start of foo or bar:

^((?!foo|bar).) @.*$

Demo on regex101

CodePudding user response:

You can try this:

^(?!.*(?:foo|bar).*@).*?@.*$

Explanation: A simple and single negative look ahead to make sure that foo or bar doesn't exist before @. Since it is a single look ahead so it operates faster.

Demo

Sample Source:

const regex = /^(?!.*(?:foo|bar).*@).*?@.*$/gm;

const str = `I do NOT want these:
[email protected]
[email protected]
[email protected]
I want these:
[email protected]
[email protected]
[email protected]`;
let m;

while ((m = regex.exec(str)) !== null) {
    if (m.index === regex.lastIndex) {
        regex.lastIndex  ;
    }
    m.forEach((match, groupIndex) => {
        console.log(`${match}`);
    });
}

  • Related