Substitution regex
I want to substitute all white sp开发者_如何学Goace that precedes the class [A-Za-z0-9_]
, with $
.
$string = "STRING sDir = sDrive";
$string =~ s/\s(?=[A-Za-z0-9_])/ \$/;
It only matches one time and produces:
STRING $sDir = sDrive;
To match multiple times, use the /g flag:
$string = "STRING sDir = sDrive";
$string =~ s/\s(?=[A-Za-z0-9_])/ \$/g;
You can use the g
flag for your regex:
$string = "STRING sDir = sDrive";
$string =~ s/\s(?=[A-Za-z0-9_])/ \$/g;
so that the s///
will operate for every match for your pattern.
Default Perl behavior is to perform the substitution once.
The g
flag tells it to perform the substitution for every occurrence.
if I think you mean what you mean:
s/\s+\b/ \$/g;
this removes all whitespace before (so ' a'
-> ' $a'
) and \b is an assertion of either (?=(?<=\W)\w)
or (?=(<=\w)\W_
; \s is always \W
, and [a-zA-Z0-9_]
matches the common definition of \w
, so it matches your (?=[...])
.
(of course, if you're dealing with character sets in which \w
is not the same as [a-zA-Z0-9]
, you'll have to substitute \b
for the assertion.)
精彩评论