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

I'm looking for a regexp which matches if the string is non-empty AND either empty or if the first non-space character in the string is not a digit. The string is guaranteed to contain no \n.

Of course I can do it with

/^\s*[^\s\d]|^$/
but I wonder if there are simpler/more elegant solutions.

updated correction about handling of empty string
-- 
Ronald Fischer <ynnor@mm.st>

Replies are listed 'Best First'.
Re: Ideas to improve this regexp?
by moritz (Cardinal) on Nov 03, 2009 at 13:43 UTC
    Your regex does match the empty string, which it should not from your descriptions. So remove the |^$ part.

    You can also write your regex as /\A(?>\s*)\D/, where (?>\s*) means grab all whitespaces and don't give them up for backtracking.

    I don't know if you consider that more simple or elegant, though.

    Perl 6 - links to (nearly) everything that is Perl 6.
      Your regex does match the empty string, which it should not from your descriptions.

      My mistake in wording the question. I've updated the post.

      I like your alternative suggestion too, but as you already suspected, it is not much simpler anyway.
      -- 
      Ronald Fischer <ynnor@mm.st>
Re: Ideas to improve this regexp?
by johngg (Canon) on Nov 03, 2009 at 14:37 UTC

    This seems to work if you don't let the engine give any spaces back by switching off backtracking.

    $ perl -le ' > print > qq{->$_<-: }, > m{(?x) ^ (?: \z | (?> \s* ) \D ) } > ? q{matches} > : q{no match} > for q{}, q{12ab}, q{cat}, q{ 99balloons}, q{ dog};' -><-: matches ->12ab<-: no match ->cat<-: matches -> 99balloons<-: no match -> dog<-: matches $

    I hope this is of interest.

    Cheers,

    JohnGG

Re: Ideas to improve this regexp?
by gmargo (Hermit) on Nov 03, 2009 at 13:54 UTC
      That doesn't work as expected. If the string starts with a whitespace followed by a digit, \s* matches the empty string and \D the whitespace, so you'll get false positives.