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 (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 surveying the Monastery: (10)
As of 2015-08-03 17:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The oldest computer book still on my shelves (or on my digital media) is ...













    Results (47 votes), past polls