Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine these regular expressions?

Tags:

regex

perl

Four very identical regular expressions. I am replacing the strings with the following scalar values. How can this be more efficient?

$line =~ s/\[(receiver)\]/$receiver/g;
$line =~ s/\[(place)\]/$place/g;
$line =~ s/\[(position)\]/$position/g;
$line =~ s/\[(company)\]/$company/g;

Thank you.

like image 932
Sean Avatar asked Oct 21 '12 06:10

Sean


People also ask

How do I join two regular expressions?

to combine two expressions or more, put every expression in brackets, and use: *?

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.


2 Answers

Consider just using a real templating system. Template Toolkit for instance is very easy.

Leaving that aside, you say you want it more efficient. Is its current perceived inefficiency a problem? If not, leave it alone.

You could do it all in one pass:

my %subst = (
    'receiver' => $receiver,
    'place'    => $place, 
    'position' => $position,
    'company'  => $company,
);
$line =~ s/\[(receiver|place|position|company)\]/$subst{$1}/g;

but this will act differently if, for instance, $receiver is 'place'.

like image 62
ysth Avatar answered Sep 18 '22 06:09

ysth


Ok, let's see, what you want:

if you want to 'evaluate' the value of variable, that name you found in the string, then, you need:

my $receiver = 'rcv';
my $place = 'plc';
my $position = 'pstn';
my $company = 'cmpn';
my $allVariableNames = join('|',qw(receiver place position company));
$line = '[receiver]';
$line =~ s/\[($allVariableNames)\]/'$'.$1/eg;
#$line =~ s/\[($allVariableNames)\]/eval('$'.$1)/eg; <- smarter and shorter variant
print $line,"\n"; #contain $receiver
print eval($line), "\n";   # evaluate ($receiver) => get rcv

it is another way to do this task, see ysth' answer above

like image 45
gaussblurinc Avatar answered Sep 19 '22 06:09

gaussblurinc