Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
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
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;

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

      Thank you

      McA

        Hi Ken,

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

        Look at my update.

        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 imbibing at the Monastery: (6)
As of 2015-07-02 00:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (25 votes), past polls