Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

How to do multiple substitutions with one RegEx?

by vennila (Novice)
on May 06, 2010 at 06:18 UTC ( [id://838646]=perlquestion: print w/replies, xml ) Need Help??

vennila has asked for the wisdom of the Perl Monks concerning the following question:

How to mention more than one operation in substitution . Like,
use strict; use warnings; my $string="welcomezxyaaaaa"; $string=~s/([b-w]+)[^a]+([a]+)/uc($1)/ge; print $string;
In the above code,I want to upper case both the $1 and $2 in the string.How to do it?

Replies are listed 'Best First'.
Re: How to do multiple substitutions with one RegEx?
by graff (Chancellor) on May 06, 2010 at 07:04 UTC
    If I understand your question...
    $string=~s/([b-w]+)([^a]+)([a]+)/uc($1).$2.uc($3)/e;
    Or, without putting eval code in the replacement:
    $string=~s/([b-w]+)([^a]+)([a]+)/\U$1\E$2\U$3/;
Re: How to do multiple substitutions with one RegEx?
by almut (Canon) on May 06, 2010 at 07:09 UTC

    As already said, when you specify eval (/e), you can use any valid Perl code for the substitution, such as string concatenation.

    In the special case here (i.e. upper-casing), and because the substitution side by default acts like a double quoted string, you could also make use of \U...\E and just interpolate $1 and $2, so you don't need eval.

    Both of these variants would produce "WELCOME foo AAAAA" with your input:

    $string=~s/([b-w]+)[^a]+([a]+)/uc($1)." foo ".uc($2)/ge; $string=~s/([b-w]+)[^a]+([a]+)/\U$1\E foo \U$2\E/g; # without /e
      Thanks to all.
Re: How to do multiple substitutions with one RegEx?
by k_manimuthu (Monk) on May 06, 2010 at 06:38 UTC
    $string=~s/([b-w]+)[^a]+([a]+)/uc($1)." Your Text ".uc($2)/ge;
    while you use evaluation in regex part, you will be use the concat operator.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://838646]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-24 07:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found