in reply to replace a digit with another digit

If you need to match against the letter as well, a regex like this will work:
s/(?<=[a-zA-Z])[12]/ $& == 1 ? 2 : 1 /eg;

Replies are listed 'Best First'.
Re^2: replace a digit with another digit
by Transient (Hermit) on Aug 17, 2005 at 18:52 UTC
    Just as an aside, according to perlvar (about $&):
    The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches.


    It might be 'better' to do:
    s/(?<=[a-zA-Z])([12])/ $1 == 1 ? 2 : 1 /eg;
    (although I have to say I'm not sure why you'd need the positive look-behind instead of just a normal match?)
      heh. I had a capture and $1 in there orginally, and then to be 'clever' changed it to $& to save a couple characters :)

      As far as the positive look-behind, y, it's not necessary -- just (since it's zero-width) saves having to reference a second capture in the replacement:
      s/([a-z])([12])/ $1 . ($2 == 1 ? 2 : 1) /eig;
      (i think the /i is less efficient, too.. too many different ways to write this one)
        Thanks !!!! The 3 lines of code below work! The first char will always be a capital letter and the 2nd char will always be a number. Then I just need to change the number. So, I think the "." in line 3 will also be ok? I am curious how lines 2 and 3 below work.

        line 2 below ... it searches for a leter in lowercase. Then it joins what it changes in the next step.... If $2 is equal to 1 then change it to 2. If $2 is equal to 2, then it changes it to 1.

        Is the letter $0 and the number $1 ? I assume so.

        example input is "D1"
        # s/(?<=[a-zA-Z])([12])/ $1 == 1 ? 2 : 1 /eg; # s/([a-z])([12])/ $1 . ($2 == 1 ? 2 : 1) /eig; s/(.)([12])/ $1 . ($2 == 1 ? 2 : 1) /eig; this might work: s/([A-Z])([12])/ $1 . ($2 == 1 ? 2 : 1) /eig;
        THANKS TO EVERYONE !!!! Kevin