Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

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/';


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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2015-12-01 02:27 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (791 votes), past polls