I have a string like 'a b b b a' and want to replace every 'b' in that string that has a whitespace before and after the character with a different character. 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. How could I write the regex to get the right behaviour?
I have a string like 'a b b b a' and want to replace every 'b' in that string that has a whitespace before and after the character with a different character. 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. How could I write the regex to get the right behaviour?
Share Improve this question asked Oct 19, 2016 at 11:56 JohnJohn 9854 gold badges14 silver badges30 bronze badges 2-
a+
instead of onlya
– mic4ael Commented Oct 19, 2016 at 11:58 - Regex is reading each character waiting to get ' a ' when it reaches the first one like so: 'x[ a ]a a x' it replaces it and continues on to the next bit 'a a x'. It skips the next 'a' since it doesn't have a space before it, ignoring that 'a'. Thats why you get 'x b a b x' – Some Dinosaur Commented Oct 19, 2016 at 12:05
3 Answers
Reset to default 6Use a lookahead after " a" to match overlapping substrings:
/ a(?= )/g
Or, to match any whitespace, replace spaces with \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).
See the regex demo
var regex = / a(?= )/g;
var strs = ['x a y a x', 'x a a a 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 i.e a positive lookahead based regex:
str = str.replace(/( )a(?= )/g, "\1b");
RegEx Demo
( )a
will match a space beforea
and capture it in group #1 followed bya
(?= )
will assert presence of a space aftera
but won't consume it in the match.
You can use RegExp with g
flag with the replace
method. Try this
var mystring = "this is a a a a a a test"
mystring.replace(/ a /g , "b");
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744144303a4560349.html
评论列表(0条)