It's very useful to 'factor' regexes as one would factor subroutines. The relationships of the parts to each other and to the whole are clarified, and it becomes easier to change a part when necessary. This clarity and ease of maintenance can be important for complex regexes (or for simple regexes when you're trying to debug one at 3 AM!).

>perl -wMstrict -le "my $prefix = qr{ (?i) \b tbgl_ }xms; my $word = qr{ \w+ }xms; my $suffix = '_gl'; ;; print '--- output ---'; for my $pw (@ARGV) { (my $ws = $pw) =~ s{ $prefix ($word) }{$1$suffix}xmsg; print qq{'$pw' -> '$ws'}; } " "tbgl_foo xxx %$# tbgl_bar()" "TBGL_foo tBgL_bar" "tbgl tbglfoo tbgl_" "tbgl_%$# Xtbgl_foo" --- output --- 'tbgl_foo xxx %$# tbgl_bar()' -> 'foo_gl xxx %$# bar_gl()' 'TBGL_foo tBgL_bar' -> 'foo_gl bar_gl' 'tbgl tbglfoo tbgl_' -> 'tbgl tbglfoo tbgl_' 'tbgl_%$# Xtbgl_foo' -> 'tbgl_%$# Xtbgl_foo'

In the example above, it was only necessary to change the definition of  $prefix from
    my $prefix = qr{ \b tbgl_ }xms;
to
    my $prefix = qr{ (?i) \b tbgl_ }xms;
when somebody said "Oh, by the way, the prefix pattern is supposed to be case insensitive."

One could use the /i regex modifier (see Modifiers in perlre) instead of the  (?i) extended pattern (see Extended Patterns in perlre) to make  $prefix case insensitive, but the latter is less easy to overlook.


In reply to Re: regex replace problem by AnomalousMonk
in thread regex replace problem 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.