Reputation: 392
I have the string "email|text|email|print|"
I would like the output to be the last string in between the two vertical bars.
I have tried
word("email|text|email|print|", -2, sep = "|")
no luck
I would like the output to just be "print"
Upvotes: 0
Views: 36
Reputation: 21400
An alternative is using lookbehind and lookahead:
x <- "email|text|email|print|"
library(stringr)
str_extract(x, "(?<=\\|)\\w+(?=\\|$)")
[1] "print"
The pattern (?<=\\|)\\w+(?=\\|$)
can be glossed as saying: "if you see a |
on the left and a |
on the right followed immediately by the string end $
, then extract the alphanumeric string in-between"
Using word
you could add the function fixed
to avoid having to escape |
:
word("email|text|email|print|", -2, sep = fixed("|"))
Upvotes: 2
Reputation: 887128
The |
is a regex metacharacter. We need to escape (\\
) or place it inside square bracket ("[|]"
) to get the literal value
library(stringr)
word("email|text|email|print|", -2, sep = "\\|")
#[1] "print"
Upvotes: 3