Reputation: 10063
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?
Upvotes: 4
Views: 117
Reputation: 59970
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 )
Upvotes: 5
Reputation: 578
don know in which platform you are going to use
pattern = (([^_]+_){3}[^_]+)_(.*)
replacement = $1.$2 // concat 1 and 2
Upvotes: 5