Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

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


Replies are listed 'Best First'.
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.


      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?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://185993]
Approved by broquaint
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2023-12-10 10:48 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (39 votes). Check out past polls.