Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Regex split string into n-length

by McA (Priest)
on Sep 10, 2013 at 07:07 UTC ( #1053177=note: print w/ replies, xml ) Need Help??


in reply to Regex split string into n-length

$string =~ s/(\w\w\w)/$1-/g;

UPDATE: As Ken pointed out correctly, this solution is wrong as it puts an additional - in a case like '123456'.

So, putting a negative lookahead to the pattern should do the trick:

$string =~ s/(\w\w\w)(?!$)/$1-/g;

McA


Comment on Re: Regex split string into n-length
Select or Download Code
Replies are listed 'Best First'.
Re^2: Regex split string into n-length (\K 5.010)
by Anonymous Monk on Sep 10, 2013 at 07:37 UTC
    use 5.009005; $string =~ s/\w{3}\K/-/g;

        Hi Ken,

        You are absolutly right. Thank you for showing this error.

        Look at my update.

        McA

      \K, these are the little pearls in Perl. ++

      Thank you

      McA

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2016-02-12 01:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?





    Results (386 votes), past polls