Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Regex split string into n-length

by McA (Curate)
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 taking refuge in the Monastery: (5)
As of 2014-09-19 03:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (129 votes), past polls