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


In reply to Validating Regular Expression by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.