Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Hi,
I have some code that accepts a string from a user to use as a regular expression in a filter. (E.g if they want the script to output a list of items beginning abc they would enter ^abc .)
This bit works well when they enter a valid regular expression. However I'm struggling with a way of validating the regexp prior to using it (ie make sure they've entered a valid regexp, not worried at this stage what it matches just that it's a valid string). The best I've come up with it
use strict; use warnings; print validate('a*') . "\n"; print validate('*') . "\n"; sub validate{ my $pat = shift; if (eval{qr/$pat/}){ return 1; }else{ return 0; } }
This works but feels like a rather ugly way to do this. Can anyone think of a better way?
I can't just use \Q and \E, I want them to be able to enter meta characters.
Thanks
Graham
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Validating Regular Expression
by davido (Cardinal) on Feb 15, 2011 at 16:29 UTC | |
by ikegami (Patriarch) on Feb 15, 2011 at 17:46 UTC | |
by kennethk (Abbot) on Feb 15, 2011 at 16:42 UTC | |
by Anonymous Monk on Feb 15, 2011 at 17:54 UTC | |
by JavaFan (Canon) on Feb 15, 2011 at 16:53 UTC | |
by Anonymous Monk on Feb 15, 2011 at 16:37 UTC | |
|
Re: Validating Regular Expression
by kennethk (Abbot) on Feb 15, 2011 at 16:25 UTC | |
by ikegami (Patriarch) on Feb 15, 2011 at 17:06 UTC | |
by ikegami (Patriarch) on Feb 15, 2011 at 17:35 UTC | |
by kennethk (Abbot) on Feb 15, 2011 at 17:53 UTC | |
by ikegami (Patriarch) on Feb 15, 2011 at 18:15 UTC |