Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract part of string between two different patterns

I try to use stringr package to extract part of a string, which is between two particular patterns.

For example, I have:

my.string <- "nanaqwertybaba"
left.border  <- "nana"
right.border <- "baba"

and by the use of str_extract(string, pattern) function (where pattern is defined by a POSIX regular expression) I would like to receive:

"qwerty"

Solutions from Google did not work.

like image 502
Marta Karas Avatar asked Apr 07 '14 22:04

Marta Karas


2 Answers

In base R you can use gsub. The parentheses in the pattern create numbered capturing groups. Here we select the second group in the replacement, i.e. the group between the borders. The . matches any character. The * means that there is zero or more of the preceeding element

gsub(pattern = "(.*nana)(.*)(baba.*)",
     replacement = "\\2",
     x = "xxxnanaRisnicebabayyy")
# "Risnice"
like image 157
Henrik Avatar answered Oct 20 '22 19:10

Henrik


I do not know whether and how this is possible with functions provided by stringr but you can also use base regexpr and substring:

pattern <- paste0("(?<=", left.border, ")[a-z]+(?=", right.border, ")")
# "(?<=nana)[a-z]+(?=baba)"

rx <- regexpr(pattern, text=my.string, perl=TRUE)
# [1] 5
# attr(,"match.length")
# [1] 6

substring(my.string, rx, rx+attr(rx, "match.length")-1)
# [1] "qwerty"
like image 34
sgibb Avatar answered Oct 20 '22 20:10

sgibb