Replace Nth occurrence of a character in a string with something else

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"

Tags:

Regex

R