For this example, at least, I don't think I'd bother with a regex. Instead, I'd split the string up into individual characters, process each character, and join the results back into a string:
my $word = 'layer'; my $new_word = join '', map { "[$_]" } split '', $word; # Or, if I want to be more explicit about the process: # my @raw_chars = split '', $word; # my @cooked_chars = map { "[$_]" } @raw_chars; # my $new_word = join '', @cooked_chars;

Edit: As pointed out in replies, the spec was to only bracket characters in the range a-zA-Z, not all characters. This can be fixed with a minor adjustment to the map. Change it to map { $_ =~ /[a-zA-Z]/ ? "[$_]" : $_ } and you get the result:

$ perl -E '$word = "layer123 $-.% foo"; $new_word = join "", map { $_ +=~ /[a-zA-Z]/ ? "[$_]" : $_ } split "", $word; say $new_word;' [l][a][y][e][r]123 0.% [f][o][o]

In reply to Re: regex find and replace with a twist by dsheroh
in thread regex find and replace with a twist 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.