jmiller@crl.dec.com (05/03/91)
Has anyone got a short (preferably) piece of Perl code to test a string to see whether or not it is a valid regular expression for use in Perl? I've written a program that allows users to type a string and then uses that to match against a data base; unfortunately the program blows up if the user types in an invalid string! --Jim
merlyn@iwarp.intel.com (Randal L. Schwartz) (05/03/91)
In article <9105021740.AA06244@peanut.crl.dec.com>, jmiller@crl writes: | Has anyone got a short (preferably) piece of Perl code to test a | string to see whether or not it is a valid regular expression for use | in Perl? I've written a program that allows users to type a string | and then uses that to match against a data base; unfortunately the | program blows up if the user types in an invalid string! Do it inside an eval, and test $@ to see if it compiled properly. eval 'Just_another_Perl_hacker,'; $_ = $@; s/.*"(.*)".*/$1/; s/_/ /g; print -- /=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\ | on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III | | merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn | \=Cute Quote: "Intel: putting the 'backward' in 'backward compatible'..."====/
allbery@NCoast.ORG (Brandon S. Allbery KB8JRR/AA) (05/03/91)
As quoted from <9105021740.AA06244@peanut.crl.dec.com> by jmiller@crl.dec.com: +--------------- | Has anyone got a short (preferably) piece of Perl code to test a | string to see whether or not it is a valid regular expression for use | in Perl? I've written a program that allows users to type a string | and then uses that to match against a data base; unfortunately the | program blows up if the user types in an invalid string! +--------------- Well, the trivial way is: eval '/$trial_regexp/; 1' || print "Invalid regexp: $@"; I.e. let the "eval" run it. If the eval bombs, it will return 0, else 1 (because we told it to). The error message that would have splattered onto the terminal is in $@. ++Brandon -- Me: Brandon S. Allbery Ham: KB8JRR/AA 10m,6m,2m,220,440,1.2 Internet: allbery@NCoast.ORG (restricted HF at present) Delphi: ALLBERY AMPR: kb8jrr.AmPR.ORG [44.70.4.88] uunet!usenet.ins.cwru.edu!ncoast!allbery KB8JRR @ WA8BXN.OH