Replace the fourth occurrence of a character in a string

I tried to replace the fourth occurrence of "_" in a string. For instance,

Enter

AAA_BBB_CCC_DD_D_EEE

Output

AAA_BBB_CCC_DDD_EEE

Can anyone suggest a solution?

+4
source share
2 answers

You can use the backlink ....

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

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

gsub( "((_[^_]+){3})_" , "\\1" , x )
+5
source

I don’t know which platform you are going to use.

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

Source: https://habr.com/ru/post/1543552/


All Articles