... this seems to work?
Actually, no! Let's try it.
knoppix@Microknoppix:~$ perl -E '
> $_ = q{bbaaccbab sdcbalsbadcbnw};
> s/(\s\w+)ba/\1Ba/g;
> say;'
bbaaccbab sdcbalsBadcbnw
knoppix@Microknoppix:~$
Notice how it has changed the second 'ba' to the right of the space rather than the first; that's because your \w+ is greedy so it matches as many characters as it can. Correcting that and running again.
knoppix@Microknoppix:~$ perl -E '
> $_ = q{bbaaccbab sdcbalsbadcbnw};
> s/(\s\w+?)ba/\1Ba/g;
> say;'
bbaaccbab sdcBalsbadcbnw
knoppix@Microknoppix:~$
Now we have changed the first 'ba' but, hang on, the second 'ba' has not been changed. That's because after the first replacement the regex engine has consumed the string up to and including the first 'ba' and is positioned in front of the next character, the 'l'. When the next match is attempted you are looking for a space followed by word characters but there is no space there so the match fails. If we try to correct that by making the space optional then the match does work more than once but the 'ba' sequences to the left of the space also get changed.
knoppix@Microknoppix:~$ perl -E '
> $_ = q{bbaaccbab sdcbalsbadcbnw};
> s/(\s?\w+?)ba/\1Ba/g;
> say;'
bBaaccBab sdcBalsBadcbnw
knoppix@Microknoppix:~$
It seems, perhaps, that this problem is a bit tricky to solve without using look-around assertions.
|