Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Validating a Regexp

by PetaMem (Priest)
on Jul 29, 2002 at 14:35 UTC ( [id://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

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.
    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
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2024-12-06 08:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which IDE have you been most impressed by?













    Results (39 votes). Check out past polls.