Best R regex for intercepting a fragment in the middle of a string?

Viewed 42

How do I construct a regex to detect the entire middle chunk of a string, so I can gsbu it out? Here's an example of what I'm aiming to do.

MATCH: enter > shop.christopherspenn.com/test > convert
MATCH: enter > shop.christopherspenn.com/page5 > convert
MATCH: enter > shop.christopherspenn.com/ > convert
NO MATCH: enter > christopherspenn.com/test > convert

The goal is to find something like shop.christopherspenn.com/test > and be able to delete it from the string.

I've tried gsub("(shop.christopherspenn.com.*)/ > ","",string) as my call but it's not able to grab the appropriate chunks.

Thanks in advance for any advice!

1 Answers

You can use

string <- c("enter > shop.christopherspenn.com/test > convert","enter > shop.christopherspenn.com/page5 > convert","enter > shop.christopherspenn.com/ > convert","enter > christopherspenn.com/test > convert")
sub('\\bshop\\.christopherspenn\\.com[^>]*>\\s*', '', string)

See the online R demo and the regex demo. Output:

[1] "enter > convert"                            
[2] "enter > convert"                            
[3] "enter > convert"                            
[4] "enter > christopherspenn.com/test > convert"

Details:

  • \b - a word boundary
  • shop\.christopherspenn\.com - a shop.christopherspenn.com string
  • [^>]* - zero or more chars other than >
  • > - a > char
  • \s* - zero or more whitespaces.
Related