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

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;

      That adds a terminal "-" whenever the string's length is a multiple of 3:

      $ perl -Mstrict -Mwarnings -E ' my @list = qw{12 123 1234 12345 123456 1234567 234 2345 23456}; for (@list) { s/\w{3}\K/-/g; say; } ' 12 123- 123-4 123-45 123-456- 123-456-7 234- 234-5 234-56

      -- Ken

        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