[prev in list] [next in list] [prev in thread] [next in thread]
List: ruby-talk
Subject: Regex replacement problem---replace every n-th
From: junk5 () microserf ! org ! uk
Date: 2006-03-01 12:03:37
Message-ID: 1141214344.988396.287290 () j33g2000cwa ! googlegroups ! com
[Download RAW message or body]
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.
So far I have:
'1 20 3 400 5 60 7 800 9 0 '.sub(/(\d* \d* )/) {|s| s + "\n"}
=> "1 20 \n3 400 5 60 7 800 9 0 "
But how do I get the substitution to be 'repeated'? Changing the regexp
to /(\d* \d*)*/ does not do what I want.
Also, I'm planning to run this on a large string, so I'd like it to be
efficient if possible.
Thanks in advance
C
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic