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

I want to use a regex to replace negative numbers with "S" and positive ones with "L". I expect the numbers to be multiple digits (so, "123" should produce "L", "-13763" should produce "S").

Should be simple, but I want to do it in a single regex if possible. Obviously possible to do in many ways, but I'd like to limit this to regexes to fit it neatly into my overall scheme. Any advice?

Replies are listed 'Best First'.
Re: Regex Substitution
by Eimi Metamorphoumai (Deacon) on Dec 02, 2004 at 20:29 UTC
    Really, I think it would be a lot nicer/cleaner/simpler to do it in real code, but...the real question is, what do you do with zero? In the code below, it'll produce "Q" (just because), but it's easily modified to do anything else.
    s/(-?\d+)/$1>0 ? "L" : ($1 == 0 ? "Q" : "S")/e;
    Or fancier, but more cryptic
    s/(-?\d+)/qw(Q L S)[$1 <=> 0]/e;
      s/(-)?(\d+)/ $1 ? "S" : $2 ? "L" : "Q" /e;

      Skips the numeric conversion part. :-)

      ---
      demerphq

      Hi,

      Just in case you need to support decimal numbers, here is an extended version of Eimi's answer:

      s/(-?\d+(\.\d+)?)/$1>0 ? "L" : ($1 == 0 ? "Q" : "S")/e; or s/(-?\d+(\.\d+)?)/qw(Q L S)[$1 <=> 0]/e;

      and add support of scientific notation:

      s/(-?\d+(\.\d+)?([Ee][+-]?\d+)?)/ ...

      Ted Young

      ($$<<$$=>$$<=>$$<=$$>>$$) always returns 1. :-)
      beautiful. . .

      I agree about the nicer/cleaner/simpler. . . I do feel that in addition to helping me with my immediate issue, however, my perl knowledge has been advanced -- thanks.

      And actually, what I do with zeros is set the result to null, which I can do before (or now, during) this operation.