Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract nth element from underscore separated string

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading