Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Use Regular Expression to add spaces to a string

by petdance (Parson)
on Mar 26, 2012 at 21:42 UTC ( #961762=note: print w/ replies, xml ) Need Help??


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


Comment on Re: Use Regular Expression to add spaces to a string
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://961762]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (14)
As of 2014-07-14 12:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (259 votes), past polls