Hey there fellow Monks, at my work, we've got a whole long list of regexes for parsing and organizing various information. These regexes are in the dozens, and are scattered across several scripts and libraries. What I'd like to do is store all of these regexes along with their mapping data in a database, so that review and maintenance of these mappings is easier.

My question is whether this is safe to do or not. If so, could you please share any potential unsafe examples?

I've drummed up a quick test scenario to ensure the building of regexes from strings gathered externally does seem to work ok:

String regex file:

a.*z ^\d+$ ^\d{4}[AZ]\d$

Test script:

use warnings; use strict; use Test::More; # Retrieve regexes from a text file (or database) as strings, regexify + them, # then use them in code my $re_file = 'regexes.txt'; open my $fh, '<', $re_file or die "Can't open $re_file: $!"; my $strings = strings(); my $i = 1; while (my $str_re = <$fh>) { chomp $str_re; my $re = qr/$str_re/; for (@{ $strings->{$i}{match} }) { is $_ =~ $re, 1, "$_ matches $str_re ok"; } for (@{ $strings->{$i}{nomatch} }) { is $_ =~ $re, '', "$_ doesn't match $str_re ok"; } $i++; } done_testing; sub strings { return { 1 => { match => [ qw( a123z az a!$@Zz ), ], nomatch => [ qw( Az aZ a213Z 99 ) ], }, 2 => { match => [ qw( 1 9999 6472323432 ), ], nomatch => [ qw( a1 1a 1! aaaa ) ], }, 3 => { match => [ qw( 2021Z1 2021A1 ), ], nomatch => [ qw( A9 123A9 1234a9 12349 1234A99999999 1234AZ9 ) ], }, }; }

In reply to Is it safe to use external strings for regexes? by stevieb

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.