tags:

views:

58

answers:

3

I want to substitute all white space 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;
+2  A: 

To match multiple times, use the /g flag:

$string = "STRING sDir = sDrive";
$string =~ s/\s(?=[A-Za-z0-9_])/ \$/g;
ysth
+2  A: 

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.

benzebuth
This will replace tabs, newlines and other whitespace with a 'space' too, so be careful. Or just replace the regex with `s/(\s)(?=[A-Za-z0-9_])/$1\$/g`. Also you could try `s/(?<=\s)(?=[A-Za-z0-9_])/\$/g`. Both are untested, but the former should work for sure.
manixrock
right, i was focusing on the repetition thing.
benzebuth
Thanks. This works just fine.
Speedyshady
A: 

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.)

sreservoir