Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Validating a Regexp

by PetaMem (Priest)
on Jul 29, 2002 at 14:35 UTC ( #185993=perlquestion: print w/ replies, xml ) Need Help??
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

Comment on Validating a Regexp
Select or Download Code
Re: Validating a Regexp
by broquaint (Abbot) on Jul 29, 2002 at 14: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
Node Status?
node history
Node Type: perlquestion [id://185993]
Approved by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2014-12-25 02:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (159 votes), past polls