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

Hello monks, I'm trying to write a regex to switch some ports in a design. I have an array of values, one of them is say:
\u0/r0/rcnt[3]
I then have a cell like so:
NOR2X0 U2905 ( .IN1(\u0/r0/rcnt[3] ), .IN2(\u0/r0/n43 ), .QN(n1699) ) +;
I need to switch the values in after the brackets in .IN1 and .IN2 so the output should be:
NOR2X0 U2905 ( .IN1(\u0/r0/n43 ), .IN2(\u0/r0/rcnt[3] ), .QN(n1699) +);
The part of the code doing that right now is:
foreach my $val (@nets_q) { $data =~ s/( [NOR|OR].*.IN1\()($val)(\).*IN2\()([^\)]*)(.*)/$1$4$3 +$2$5/g; }
But this throws an error:
Unrecognized escape \u passed through in regex;
So it is considering the "\u" part of "\u0/ro/rcnt3" as an escape character. How would I go about doing this? Is this the right way? Thanks in advance!

Replies are listed 'Best First'.
Re: Passing a variable to a regex
by choroba (Cardinal) on Sep 17, 2015 at 10:37 UTC
    Run quotemeta on $val, or use \Q$val\E in the regex.

    Update: I also had to add a space to the regex:

    s/( [NOR|OR].*.IN1\()(\Q$val\E)( \).*IN2\()([^)]*)(.*)/$1$4$3$2$5/g; # ^
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Thank you, that worked perfectly! Also I appreciate catching the space, I would've lost a lot of time figuring that out. A very small amount of the cases had that space there, I guess I got lucky.
Re: Passing a variable to a regex
by Athanasius (Archbishop) on Sep 17, 2015 at 11:17 UTC

    Hello mavericknik,

    I see choroba has answered your question, but I wanted to ask: what is [NOR|OR] supposed to do in the regex? It is actually a character class, which matches any one character from the list “N”, “O”, “R”, “|”:

    21:10 >perl -wE "my $s = ' NOR42'; $s =~ / [NOR|OR](.*)/; say $1;" OR42 21:10 >

    Did you mean to write this: (?:NOR|OR)? If so, it can be shortened to: N?OR.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Wow thanks a lot for that! I was just going through the results after fixing the script and getting weird results. Makes sense now!