d3hero23
d3hero23

Reputation: 392

Extract Text inbetween the last two | delimiters in r

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

Answers (2)

Chris Ruehlemann
Chris Ruehlemann

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 wordyou could add the function fixed to avoid having to escape |:

word("email|text|email|print|", -2, sep = fixed("|")) 

Upvotes: 2

akrun
akrun

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

Related Questions