Dorian06
Dorian06

Reputation: 49

Substitution regex

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;

Upvotes: 0

Views: 225

Answers (3)

benzebuth
benzebuth

Reputation: 695

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.

Upvotes: 2

muhmuhten
muhmuhten

Reputation: 3341

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

Upvotes: 0

ysth
ysth

Reputation: 98388

To match multiple times, use the /g flag:

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

Upvotes: 3

Related Questions