Tarun Das
Tarun Das

Reputation: 35

Selecting a specific letters from a character after a specific symbol

Need to take out all the characters before "(" and combine them with ";"

stringr::word(pilist, 2, sep = '(\\s*|\\')

pilist = "pi1(tag1,tag2);pi2(tag3,tag4,tag5);"

I expect the output as

"pi1;pi2"

Upvotes: 1

Views: 44

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

You can try this pattern

\([^)]+\)|;+$

enter image description here

Regex Demo

Note:- Use escape character as \\ or \ depending on your regex engine

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388862

If you are string has the exact same structure as shown, we can remove everything which comes between round brackets and the trailing ; using gsub

gsub("\\(.*?\\)|;$", "", pilist)
#[1] "pi1;pi2"

However, following your description it can also be done by extracting the words which we want instead of removing. Using str_extract_all

paste0(stringr::str_extract_all(pilist, "(\\w+)(?=\\(.*\\))")[[1]], collapse = ";")
#[1] "pi1;pi2"

Upvotes: 1

Related Questions