[英]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.