in reply to Golf this reg ex

First, you don't have to backwhack (escape) the '.' character when it appears inside of a character class.

Next, [0-9] is the same as \d.

Third, the non-capturing parens are not helping you.

Boil that down and you get:

print "$1\n" if $number =~ m/ ^( [\d.-]* \d [\d.-]* )$ /x;

Oh, forgot to mention; the /x modifier helps to keep things clean and tidy looking.

If you really want it golfed, how about this:

$number =~ /^([\d.-]*\d[\d.-]*)$/ and print "$1\n";


Dave

Replies are listed 'Best First'.
Re: Golf this reg ex
by Abigail-II (Bishop) on Apr 16, 2004 at 09:59 UTC
    /^([\d.-]*\d[\d.-]*)$/ looks so innocent. It is however a very inefficient regex. Because you give Perl lots of ways of matching the lone \d, it can take a relatively long time for Perl to determine there is a failure. Dropping the \d from the first character class make a huge difference:
    #!/usr/bin/perl use strict; use warnings; use Benchmark qw /cmpthese/; our $re1 = qr /^[\d.-]*\d[\d.-]*$/; our $re2 = qr /^[.-]*\d[\d.-]*$/; our @strs = <DATA>; our (@d, @a); foreach (@strs) { die if /$re1/ xor /$re2/ } cmpthese -1 => { davido => 'my @a = map {/$re1/} @strs', abigail => 'my @a = map {/$re2/} @strs', } __DATA__ --1--2--3--4--5--6--7--8--9--0--1--2--3--4--5--6--7--8--9--0--a--2--3- +-4--5-- Rate davido abigail davido 23578/s -- -88% abigail 196495/s 733% --

    Abigail