Mariappan Subramanian
Mariappan Subramanian

Reputation: 10063

Replace fourth occurrence of a character in a string

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

Answers (2)

Simon O'Hanlon
Simon O'Hanlon

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

Sony George
Sony George

Reputation: 578

don know in which platform you are going to use

pattern = (([^_]+_){3}[^_]+)_(.*)
replacement = $1.$2  // concat 1 and 2

Upvotes: 5

Related Questions