Hi,


>From: Ross Bamford <rossrt / roscopeco.co.uk>
>Reply-To: ruby-talk / ruby-lang.org
>To: ruby-talk / ruby-lang.org (ruby-talk ML)
>Subject: Re: Regex replacement problem---replace every n-th
>Date: Wed, 1 Mar 2006 21:36:59 +0900
>
>On Wed, 2006-03-01 at 21:03 +0900, junk5 / microserf.org.uk wrote:
> > Hi all
> >
> > I have the string '1 20 3 400 5 60 7 800 9 0 ' and need to replace
> > every n-th space in the string with another character. So if n=2 and
> > the replacement character is '\n', then the above would become
> >
> > '1 20\n3 400\n5 60\n7 800\n9 0\n'.
> >
> > I'm sure it must be possible (easy, even) to do this with a regex
> > substitution, but unfortunately I'm no regex ninja.
>
>There's probably a better way to do this, but here's a 'metaregex' idea:
>
>	str =  "1 20 3 400 5 60 7 800 9 0 "
>	# => "1 20 3 400 5 60 7 800 9 0 "
>
>	n = 2
>	# => 2
>
>	r = Regexp.new('(' + ('\d+\s' * (n - 1)) + '\d+)(\s)')
>	# => /(\d+\s\d+)(\s)/
>
>	str.gsub(r) { $1 + rep }
>	# => "1 20\n3 400\n5 60\n7 800\n9 0\n"
>
>	n = 3
>	# => 3
>
>	r = Regexp.new('(' + ('\d+\s' * (n - 1)) + '\d+)(\s)')
>	# => /(\d+\s\d+\s\d+)(\s)/
>
>	str.gsub(r) { $1 + rep }
>	# => "1 20 3\n400 5 60\n7 800 9\n0 "
>
Here's another idea:

str =  "1 20 3 400 5 60 7 800 9 0 "
rep = "\n"
n = 2
str.gsub(/((\d+\s){#{n}})/){$1.chop+rep}



Regards,

Park Heesob