我在 javascript 中匹配 nomatch 之后的任何字串(如果有),例如在這兩種情況下的“test 1 test2”:
nomatch test1 test2
和
test1 test2
我試過https://regex101.com/r/qS4L1l/1
((?<=nomatch )\s*)(. )|(?<!nomatch )(. )
但它會包括 nomatch 而我不想。
uj5u.com熱心網友回復:
如果您以 ECMAScript 2018 兼容的 JavaScript 環境為目標,您可以使用
(?<=nomatch\s |^(?!.*nomatch\s)).
請參閱正則運算式演示。在這里,除了換行符之外的任何一個或多個字符,只有在它們前面緊跟nomatch一個空格,或者,如果當前位置是字串的開頭并且之后沒有nomatch子字串除換行符之外的任何零個或多個字符后的空格。
由于需要更換匹配的部件. ,也可以考慮使用
text.replace(/^(.*?nomatch\s )?\S.*/, '$1<NEW TEXT>')
請參閱此正則運算式演示。詳情:
^- 字串的開始(.*?nomatch\s )?- 第 1 組:任何零個或多個字符的可選序列,除了換行符,盡可能少,然后nomatch是一個或多個空格\S- 非空白.*- 線路的其余部分。
替換字串中的$1代表第 1 組值。
const texts = ['This is a nomatch test1 test2','nomatch test1 test2','test1 test2'];
const re = /^(.*?nomatch\s )?\S.*/;
for (const text of texts) {
console.log(text.replace(re, '$1<NEW TEXT>'));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457112.html
標籤:javascript 正则表达式
上一篇:設定空std::regex
