[英]Regex: match pattern in all words of a string
I have a regex pattern that matches leading characters before (a, b, c or i) in only the first word of a string: /^\\s*[^abci]+(?=\\w)/i
such that: 我有前导字符相匹配前一个正则表达式模式(A,B,C或i) 仅在字符串的第一个字: /^\\s*[^abci]+(?=\\w)/i
,使得:
"sanity".replace(/^\s*[^abi]+(?=\w)/i, (pattern) => 'v');
// "vanity"
How do i define the regex newRegex
such that it matches leading characters in every word of a string so that: 我如何定义正则表达式newRegex
,使其匹配字符串的每个单词中的前导字符,以便:
"sanity is a rice".replace(newRegex, (pattern) => 'v');
outputs: vanity is a vice 输出:虚荣是一种恶习
You can also try using split()
and map()
to remove the first char and get the desired output: 您还可以尝试使用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));
It seems to me you want to replace any word char other than a
, b
, i
at the beginning of a word. 在我看来,你想在一个单词的开头替换除a
, b
, i
之外a
任何单词char。
You may use 你可以用
.replace(/\b[^\Wabi]/gi, 'v')
See the regex demo . 请参阅正则表达式演示 。
\\b
- a word boundary \\b
- 单词边界 [^\\Wabi]
- a negated character class that matches any char other than a non-word char (so, all word chars are matched except the chars that are also present in this class), a
, b
and i
. [^\\Wabi]
- 一个否定的字符类,它匹配除非字char之外的任何字符(因此,所有字符匹配除了此类中也存在的字符外), a
, b
和i
。 The global modifier g
is added so as to match all occurrences. 添加全局修改器g
以匹配所有出现。
JS demo: JS演示:
console.log( "sanity is a rice".replace(/\\b[^\\Wabi]/gi, 'v') );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.