Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Validating a Regexp

by PetaMem (Priest)
on Jul 29, 2002 at 10:35 UTC ( [id://185993]=perlquestion: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

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

Fellow Monks,

I wonder if there is a way to validate a regexp in Perl. It'd need just a YES/NO functionality. Let's say you have something like a[hjg].* and *a[hj. The routine (my guess is that this could even be another regexp), should identify the first regexp as valid, the second as invalid.

I've been peeking around in the monastery, but only found references to the much bigger (if not impossible) task of validating perl code. But it seems to me, that a plain YES/NO regexp validation should be feasible.

Any clues? TIA

Bye
 PetaMem

Replies are listed 'Best First'.
Re: Validating a Regexp
by broquaint (Abbot) on Jul 29, 2002 at 10:41 UTC
    sub is_valid_re { eval { qr/$_[0]/ }; return $@ ? 'NO' : 'YES'; } my @regexes = qw(a[hjg].* *a[hj); print is_valid_re($_), $/ for @regexes; __output__ YES NO
    That seems to do the job.
    HTH

    _________
    broquaint

      sub is_valid_re { eval { qr/$_[0]/ }; return $@ ? 'NO' : 'YES'; }

      This eval returns a regex or undef, so you could write as follows:

      sub is_valid_re { eval { qr/$_[0] } ? 'YES' : 'NO' }
      But I'd _never_ return words when a boolean value is needed. Digits are so much nicer for that. If you want words, you could create yet another sub to turn the truth number into a word.
      sub is_valid_re { eval { qr/$_[0] } } print is_valid_re('abc') ? 'YES' : 'NO'; sub human_bool { shift ? 'YES' : 'NO' } print human_bool(is_valid_re('abc'));

      - Yes, I reinvent wheels.
      - Spam: Visit eurotraQ.
      

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://185993]
Approved by broquaint
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.