Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

r

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.

like image 600
Mahmoud Avatar asked Apr 26 '19 21:04

Mahmoud


People also ask

How do you replace a second occurrence of a character in a string in Java?

Use two parameter form of indexOf and start searching at previously found position + 1.

How do you replace a nth occurrence of a character in a string in Java?

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.


1 Answers

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"
like image 105
Pushpesh Kumar Rajwanshi Avatar answered Oct 19 '22 04:10

Pushpesh Kumar Rajwanshi