in reply to Regular Expressions with varialbe with "[]"

hi herman4016

I modified the regexp a little. You don't need memory braces because variable $& contains the match and '+?' turns the regexp non-greedy.

use strict; use warnings; use 5.010; my $port_name = 'sdm_yout_i[1]'; $port_name =~ s/\[|\]/\\$&/g; # escaping &#91; and &#93; while (<DATA>) { if ( /\.[0-9a-z_]+ \( {${port_name}.+?\)/ ) { print '$port_name = ' ; say $port_name; print 'cell name = ' ; say $&; } } __DATA__ .dout_sar ( dout_sar ) , .dcoc_status ( dcoc_status ) , .sdm_yout_i ( +{sdm_yout_i[1] , n145 } ) , .sdm_yout_q ( sdm_yout_q )

Replies are listed 'Best First'.
Re^2: Regular Expressions with varialbe with "[]"
by herman4016 (Acolyte) on Mar 12, 2015 at 02:41 UTC

    Thanks pme another method to solve , following is my code and what I want :

    #!/usr/bin/perl use 5.010; use strict; use warnings; my $port_name = 'sdm_yout_i[1]'; $port_name =~ s/\[|\]/\\$&/g; # escaping &#91; and &#93; open my $fh, "tt.txt" or die $!; while (<$fh>) { if ( /\.([0-9a-z_]+?) \( \{.*?${port_name} .*?,/ ) { print '$port_name = ' ; say $port_name; print '$cell name = ' ; say $1; } }

    Output :

    $port_name = sdm_yout_i\[1\] $cell name = sdm_yout_i