-3

Consider this simple example url

http://this-is-a-nice-example/2020.htm

I am trying to write a regex that replaces the last / with an empty space, so that the url actually reads http://this-is-a-nice-example2020.htm

Unfortunately, the regex below returns a surprising result

> str_replace('http://this-is-a-nice-example/2020.htm', regex('example([/])20'), '' )
[1] "http://this-is-a-nice-20.htm"

Any ideas? Thanks!

ℕʘʘḆḽḘ
  • 18,566
  • 34
  • 128
  • 235

1 Answers1

0

We can wrap with fixed instead of trying to escape the metacharacter with regex

library(stringr)
str_replace(url1, fixed("example/"), "example")
#[1] "http://this-is-a-nice-example2020.htm"

Or if we use regex,

str_replace(url1, regex("example/"), "example")
#[1] "http://this-is-a-nice-example2020.htm"

Or using the OP's code, we need the value in the replacement

str_replace('http://this-is-a-nice-example/2020.htm', regex('example[/]20'), 'example20' )
#[1] "http://this-is-a-nice-example2020.htm"

data

url1 <- "http://this-is-a-nice-example/2020.htm"
akrun
  • 874,273
  • 37
  • 540
  • 662