如果在其中的字符 @ 之前存在某些單詞,我想丟棄一個字串。
示例:
我想要單詞foo,bar并且不應出現在 @ 符號之前的字串上,但在 @ 符號之后允許使用相同的單詞。
我不想要這些:
abc foo[email protected]
barabc@domain foo.com
我想要這些:
abcxyz@domain foo.com
pqrabc@domain bar.com
我有 regex ^((?!(foo|bar)).)*$,但它也會丟棄在 @ 符號之后foo和bar之后的字串,即使這些詞在 @ 之前不存在。
我只希望它在字串中的 @ 符號之前出現foo或時丟棄。bar
你知道我該怎么做嗎?謝謝。
uj5u.com熱心網友回復:
您需要在 之前的每個字符位置斷言@它不是fooor的開頭bar:
^((?!foo|bar).) @.*$
正則運算式 101 上的演示
uj5u.com熱心網友回復:
你可以試試這個:
^(?!.*(?:foo|bar).*@).*?@.*$
解釋: 一個簡單而單一的否定前瞻,以確保 foo 或 bar 在 @ 之前不存在。由于它是一個單一的前瞻,所以它運行得更快。
演示
樣本來源:
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}`);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/458786.html
標籤:javascript 正则表达式
上一篇:正則運算式模式匹配某種型別的子字串(具有一定順序的字符)
下一篇:正則運算式findall模式
