-1
df <- data.frame(
    videos = c("Moon vs Grubby", "Moon vs Happy", "Happy vs Th00"),
    links = c("https://www.youtube.com/watch?v=QlNc-jb4ESk&t", "https://www.youtube.com/watch?v=VESO8YQVFSE", "https://www.youtube.com/watch?v=RI3IJT8ZzBM")
)

df$links <- as.character(df$links)
df$links <- gsub("watch?v=", "embed/", df$links)

I have got the following code with links to YouTube which I want to embed in a shiny App. However YouTube needs to replace part of the string which is interpreted as a regular expression. I did not find a helpful solution here.

So how can I gsub this pattern?

Current Links: https://www.youtube.com/watch?v=QlNc-jb4ESk&t

Expected Outcome: https://www.youtube.com/embed/=QlNc-jb4ESk&t

DSGym
  • 2,807
  • 1
  • 6
  • 18

2 Answers2

3

We need to escape the ? and = as these are metacharacters

gsub("watch\\?v\\=", "embed/=", df$links)

or with fixed = TRUE

gsub("watch?v=", "embed/=", df$links, fixed = TRUE)

Also, as there is only a single instance, we can use sub

sub("watch?v=", "embed/=", df$links, fixed = TRUE)
#[1] "https://www.youtube.com/embed/=QlNc-jb4ESk&t" 
#[2] "https://www.youtube.com/embed/=VESO8YQVFSE"  
#[3] "https://www.youtube.com/embed/=RI3IJT8ZzBM"  
akrun
  • 874,273
  • 37
  • 540
  • 662
2

My guess is that this expression might work:

(\S*)watch\?v=(\S*)

The expression is explained on the top right panel of this demo, if you wish to explore further or modify it, and in this link, you can watch how it would match against some sample inputs step by step, if you like.

and our code might look like:

gsub("(\\S*)watch\\?v\\=(\\S*)", "\\1embed/\\2", df$links)

My guess is that this would be the desired output:

https://www.youtube.com/embed/QlNc-jb4ESk&t
Emma
  • 27,428
  • 11
  • 44
  • 69