Consider a = paste(1:10,collapse=", ")
which results in
a = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10"
I would like to replace every n-th (say 4-th) occurrences of "," and replace it with something else (say "\n"). The desired output would be:
"1, 2, 3, 4\n 5, 6, 7, 8\n 9, 10"
I am looking for a code that uses gsub
(or something equivalent) and some form of regular expression
to achieve this goal.
Use two parameter form of indexOf and start searching at previously found position + 1.
An example of Java Replace nth Occurrence String:- 1) First find the index where string occurs nth time. 2) Replace the string at the given index. Test-case when the string doesn't occur in the given string.
You can replace ((?:\d+, ){3}\d),
with \1\n
You basically capture everything till fourth comma in group1 and comma separately and replace it with \1\n
which replaces matched text with group1 text and newline, giving you the intended results.
Regex Demo
R Code demo
gsub("((?:\\d+, ){3}\\d),", "\\1\n", "1, 2, 3, 4, 5, 6, 7, 8, 9, 10")
Prints,
[1] "1, 2, 3, 4\n 5, 6, 7, 8\n 9, 10"
Edit:
To generalize above solution to any text, we can change \d
to [^,]
New R code demo
gsub("((?:[^,]+, ){3}[^,]+),", "\\1\n", "1, 2, 3, 4, 5, 6, 7, 8, 9, 10")
gsub("((?:[^,]+, ){3}[^,]+),", "\\1\n", "a, bb, ccc, dddd, 500, 600, 700, 800, 900, 1000")
Output,
[1] "1, 2, 3, 4\n 5, 6, 7, 8\n 9, 10"
[1] "a, bb, ccc, dddd\n 500, 600, 700, 800\n 900, 1000"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With