[英]Javascript: Replace all occurences of ' a ' in a string with ' b ' with a regex
I have a string like 'abbba' and want to replace every 'b' in that string that has a whitespace before and after the character with a different character. 我有一个像'abbba'这样的字符串,并希望替换该字符串中的每个'b',该字符串在具有不同字符的字符之前和之后具有空格。 How could I do that with a regex? 我怎么能用正则表达式做到这一点? My idea was this: 我的想法是这样的:
'x a y a x'.replace(new RegExp(' a ', 'g'), ' b '); // is: x b y b x, should: x b y b x (correct)
'x a a a x'.replace(new RegExp(' a ', 'g'), ' b '); // is: x b a b x, should: x b b b x (wrong)
'x aa x'.replace(new RegExp(' a ', 'g'), ' b '); // is: x aa x, should: x aa x (correct)
But that regex is only working if there is not more than 1 occurence of the character next to another occurence of the character. 但是,只有在角色的另一个出现旁边出现不超过1个字符时,该正则表达式才有效。 How could I write the regex to get the right behaviour? 我怎么能写正则表达式以获得正确的行为?
Use a lookahead after " a" to match overlapping substrings: 在“a”之后使用前瞻来匹配重叠的子串:
/ a(?= )/g
Or, to match any whitespace, replace spaces with \\s
. 或者,要匹配任何空格,请用\\s
替换空格。
The lookahead , being a zero-width assertion , does not consume the text, so the space after " a" will be available for the next match (the first space in the pattern is part of the consuming pattern). 作为零宽度断言的前瞻不消耗文本,因此“a”之后的空间将可用于下一个匹配(模式中的第一个空格是消费模式的一部分)。
See the regex demo 请参阅正则表达式演示
var regex = / a(?= )/g; var strs = ['xaya x', 'xaaa x', 'x aa x']; for (var str of strs) { console.log(str,' => ', str.replace(regex, " b")); }
As your matches are overlapping, you can use zero width assertion ie a positive lookahead based regex: 由于您的匹配重叠,您可以使用零宽度断言,即基于前瞻性的正向前导:
str = str.replace(/( )a(?= )/g, "\1b");
( )a
will match a space before a
and capture it in group #1 followed by a
( )a
将前匹配的空间a
和捕捉它在组#1,接着a
(?= )
will assert presence of a space after a
but won't consume it in the match. (?= )
将后断言的空间的存在a
但在比赛中不会消耗它。 You can use RegExp with g
flag with the replace
method. 您可以将带有g
标志的RegExp与replace
方法一起使用。 Try this 尝试这个
var mystring = "this is a a a a a a test"
mystring.replace(/ a /g , "b");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.