![](/img/trans.png)
[英]How to match string between two words, and repeat this pattern for all two defined words in the string, Regex?
[英]Regex: match pattern in all words of a string
我有前導字符相匹配前一個正則表達式模式(A,B,C或i) 僅在字符串的第一個字: /^\\s*[^abci]+(?=\\w)/i
,使得:
"sanity".replace(/^\s*[^abi]+(?=\w)/i, (pattern) => 'v');
// "vanity"
我如何定義正則表達式newRegex
,使其匹配字符串的每個單詞中的前導字符,以便:
"sanity is a rice".replace(newRegex, (pattern) => 'v');
輸出:虛榮是一種惡習
您還可以嘗試使用split()
和map()
刪除第一個char並獲取所需的輸出:
function replaceChar(str){ var matchChar = ['a', 'b', 'c', 'i']; var changedArr = str.split(/\\s+/).map((item) => { if(matchChar.includes(item.charAt(1))){ return 'v' + item.substr(1, item.length); } return item; }); return changedArr.join(' '); } var str = 'sanity is a rice'; console.log(replaceChar(str)); str = 'This is a mice'; console.log(replaceChar(str));
在我看來,你想在一個單詞的開頭替換除a
, b
, i
之外a
任何單詞char。
你可以用
.replace(/\b[^\Wabi]/gi, 'v')
請參閱正則表達式演示 。
\\b
- 單詞邊界 [^\\Wabi]
- 一個否定的字符類,它匹配除非字char之外的任何字符(因此,所有字符匹配除了此類中也存在的字符外), a
, b
和i
。 添加全局修改器g
以匹配所有出現。
JS演示:
console.log( "sanity is a rice".replace(/\\b[^\\Wabi]/gi, 'v') );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.