in reply to pull out num from str

First of all, a character class already means "one of these characters", so your pipe isn't doing what you think it is. It would match |123. So that should be [+-]. It's also not necessary to escape the plus sign within a character class. Then, to say "zero or one of these," append ? to it, giving you [+-]? . You can also drop the .* from the beginning and .*$ from the end, since they're implied anyway. That gets your regex down to /([+-]?\d+)/ .

Aaron B.
My Woefully Neglected Blog, where I occasionally mention Perl.

Replies are listed 'Best First'.
Re^2: pull out num from str
by jwkrahn (Abbot) on Apr 23, 2012 at 08:45 UTC
    You can also drop the .* from the beginning

    "123 456" =~ /([+-]?\d+)/ and "123 456" =~ /.*([+-]?\d+)/ match two different things because .* at the beginning is greedy.

Re^2: pull out num from str
by icoder (Novice) on Apr 23, 2012 at 09:14 UTC
    Thanks . works exactly as expected
Re^2: pull out num from str
by icoder (Novice) on Apr 23, 2012 at 11:55 UTC
    This works fine , Is there any disadvantages of using this regex,because ,others in this thread posted lenthy regexes which will do the same thing. please suggest

      If it works with all the formats your data includes, that's what's important. As jwkrahn pointed out, by removing your leading .*, I did change the effect of yours in any case where there is more than one matching number in a string:

      $str = 'This sentence has two numbers, +13 and -15.'; $str =~ /([+-]?\d+)/; # matches +13, first match found $str =~ /.*([+-]?\d+)/; # matches -15 because .* is greedy

      So which of those you use depends on whether you want to find the first number or the last number in a line. If your lines only have one number, it won't matter.

      Aaron B.
      My Woefully Neglected Blog, where I occasionally mention Perl.