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

I am wondering if it is all possible to consolidate the following example into a single regular expression instead of using two

if ( /^[^0-9]+$/ ) { my @words= /(\b.+?\b)/g; print "@words\n"; }

All this does is match words as long as there is not a single number located anywhere in the line.

Replies are listed 'Best First'.
Re: Reg Ex help
by Chmrr (Vicar) on Sep 12, 2001 at 21:35 UTC
    How about the following:
    if (my @words = /(\b.*?\b)/g and not grep {/\d/} @words) { print @words; # Do stuff. }
    However, having two regex isn't always a bad thing. Personally, I think your code reads easier and is more intuitive; my only change would be from if (/^[^0-9]+$/) to unless (/\d/)

     
    perl -e 'print "I love $^X$\"$]!$/"#$&V"+@( NO CARRIER'

Re: Reg Ex help
by chromatic (Archbishop) on Sep 12, 2001 at 21:33 UTC
    Depending on what you consider a word, this may be a better solution:
    unless (/\d/) { @words = split(' ', $_); }
Re: Reg Ex help
by dragonchild (Archbishop) on Sep 12, 2001 at 20:30 UTC
    unless (my @words = /(\b\D+?\b)/g) { print "Houston, we have a problem.\n"; }

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      That doesn't work. He doesn't want to match at all if theres any digits anywhere in the string (or so he says :). Try "abc 123" just for example. Sometimes its just not worth trying to do something in one regex, but you could simplify to this:
      unless (tr/0-9//) { my @words = /\w+/g; print "@words\n"; }
        No, it's not identical. But, I suspect, it's closer to the spirit of what he's doing...

        ------
        We are the carpenters and bricklayers of the Information Age.

        Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: Reg Ex help
by Anarion (Hermit) on Sep 13, 2001 at 05:31 UTC

    I think you want something like:

    @words=grep{!/\d/}split;

    $anarion=\$anarion;

    s==q^QBY_^=,$_^=$[x7,print

Re: Reg Ex help
by jehuni (Pilgrim) on Sep 13, 2001 at 20:52 UTC
    !/\d/ and @words = /(\b.+?\b)/g and print "@words\n";

    -jehuni

Re: Reg Ex help
by hopes (Friar) on Sep 14, 2001 at 09:41 UTC
    How about that:

    @words=grep{$_}/(?:.*\d.*)?(\b\w+?\b)?/g;

    Note that the anonymous monk want to match anything if there is a digit in the string, and he want to use only a reg exp.
    I had problems, because I was matching '' (empty).
    The grep solves that.

    I hope this help.

    P.S. I think it would be better with two reg exp's, but we know, TIMTOWTDI

    Regards, Hopes
Re: Reg Ex help
by pike (Monk) on Sep 14, 2001 at 15:02 UTC
    How about this:

    my (@words) = /^\s*(\D+\b)+\s*$/;

    Just one regex, and should not match if the line contains digits.

    pike