http://www.perlmonks.org?node_id=961762


in reply to Use Regular Expression to add spaces to a string

Part of what you MUST do when writing a regex is to describe the transformation you want in English. An example is not enough. You might see the transformation as obvious, but we can't, and your regex certainly can't tell what you're thinking.

It seems that what you're wanting to do is this: "Take a nine-character string and change it into the first three characters, followed by a space, followed by the second three characters, followed by a hyphen, followed by the last three characters."

If that's what you want, you write it like this.

$str =~ s/^(...)(...)(...)$/$1 $2-$3/';
But that will also translate "bookstore" into "boo kst-ore". Is that OK? Or do you only want to do transformations if there are digits? Then you have to write it as:
$str =~ s/^(\d\d\d)(\d\d\d)(\d\d\d)$/$1 $2-$3/';

xoxo,
Andy