Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace fourth occurrence of a character in a string

Tags:

replace

r

I was trying to replace fourth occurrence of '_' in a string. For example,

Input

AAA_BBB_CCC_DD_D_EEE

Output

AAA_BBB_CCC_DDD_EEE

Can anyone please suggest a solution?

like image 818
Mari Avatar asked Dec 25 '22 08:12

Mari


1 Answers

You could use a back-reference....

gsub( "(_[^_]+_[^_]+_[^_]+)_" , "\\1" , x )
# [1] "AAA_BBB_CCC_DDD_EEE"

EDIT And thanks to @SonyGeorge below this could be further simplified to:

gsub( "((_[^_]+){3})_" , "\\1" , x )
like image 164
Simon O'Hanlon Avatar answered Jan 23 '23 11:01

Simon O'Hanlon