Home > Enterprise >  Extract nth element from underscore separated string
Extract nth element from underscore separated string

Time:07-20

I want to extract myproducta and myproductb.

I think by regex is ok, but only works for: cc string, but not for aa. Howcome? Both have same length.

aa <- "e220juju_uk_yy_aon_aon_conversion_mystore_facebook-network_ppl_primaria_myproducta_galaxycombos_20220520"
cc <- "e220tyty_bo_oo_aon_aon_conversion_mystore_facebook-network_ppl_lal_myproductb_wd95m4473mw_diasdecyber_20220718"

regex part:

gsub(cc, pattern = ".*_.*_.*_.*_.*_.*_.*_.*_.*_(.*)_.*_.*_.*", replacement = "\\1", perl = TRUE) #works: returns: myproductb

gsub(aa, pattern = ".*_.*_.*_.*_.*_.*_.*_.*_.*_(.*)_.*_.*_.*", replacement = "\\1", perl = TRUE) #don't work: returns: primaria

CodePudding user response:

You can use anchors and a negated character class, and then repeat 10 times matching an underscore before capturing the 11th occurrence.

^(?:[^_]*_){10}([^_]*).*$

Regex demo | R demo

aa <- "e220juju_uk_yy_aon_aon_conversion_mystore_facebook-network_ppl_primaria_myproducta_galaxycombos_20220520"
cc <- "e220tyty_bo_oo_aon_aon_conversion_mystore_facebook-network_ppl_lal_myproductb_wd95m4473mw_diasdecyber_20220718"

pattern <- "^(?:[^_]*_){10}([^_]*).*$"

gsub(pattern, "\\1", aa, perl = TRUE)
gsub(pattern, "\\1", cc, perl = TRUE)

Output:

[1] "myproducta"
[1] "myproductb"

CodePudding user response:

Here are some approaches

read.table(text = aa, sep = "_")[[11]]
## [1] "myproducta"

strsplit(aa, "_")[[1]][11]
## [1] "myproducta"

scan(text = aa, sep = "_", what = "", quiet = TRUE)[11]
## [1] "myproducta"

sub("^(([^_]*)_){10}([^_]*)_.*", "\\3", aa)
## [1] "myproducta"
  • Related