Ajey Kulkarni <[EMAIL PROTECTED]> wrote: : Subject: hi..
<sarcasm> Great subject. So much better than "Need help with regex" or "Need to escape []". Always keep us guessing. </sarcasm> : i want to 'insert' an escape character for every '[' & ']' : i will find in a variable.. : : Suppose $temp has a word which might contain [ and/or ]. : Eg: if $temp has hello] : the modified temp should have hello\] : : if $value has [hello] i want the result to be \[hello\]. : : Is there a quick one line regex to do this? : i'm able to match the presence of [ & ] : if( (/\[/)|(/\]/) ){ : my $value = $_; : $value =~ s/\[/\\\[/; : $value =~ s/\]/\\\]/; : print $value; : } A one-liner is not necessarily better. You might want to test. The substitution operator has a pattern on the left side and a replacement string on the other. According to 'perlop' it takes this form: s/PATTERN/REPLACEMENT/egimosx Let's take a look at your phrase: s/\[/\\\[/ The PATTERN is '\[' and the REPLACEMENT is "\\\[". I put the REPLACEMENT in double quotes because that is how it is most commonly interpolated. To print '\[' we need "\\[" on the REPLACEMENT side. The PATTERN side views '[', and ']' as special characters. So we need to escape them or we need to use some other means to describe them. To look for more than one we can place them in a character class: [\[\]] or as [\][] then capture the one we match: ([\][]). s/([\][])/\\$1/ We could also avoid the character class and use: s/(\]|\[)/\\$1/ To capture multiple instances in the line we add 'g'. s/([\][])/\\$1/g And to make it easier to read we add x: $value =~ s/ # start substitution ( # capture match in $1 [\][] # character class for [ and ] ) # end capture /\\$1/gx; # replace with \[ or \] globally Having said all this. I would still prefer Rob's solution with two separate regexes in a 'foreach'. HTH, Charles K. Clarkson -- Head Bottle Washer, Clarkson Energy Homes, Inc. Mobile Home Specialists 254 968-8328 -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>