Remove characters between 1) opening and closing pattern and 2) if no closing pattern, opening pattern and end

Viewed 39

Have a solution to the problem using a chain of two gsub calls - out of curiosity, I wondered if there is a shorter regex for what I want to achieve. (using solution from Remove the letters between two patterns of strings in R)

I want to remove all characters either between the occurrence of a certain pattern, or - if there is no "closing pattern", between the "opening" pattern and the end.

foostring <- c("First test *** no asterisks at the end", 
               "Second test *** asterisks in the middle *** something different",
               "Third test *** more than one asterisk *** something different *** second asterisk ***",
               "Fourth test *** asterisks followed by a special character ***_something different")

# desired output with chain of gsubs

gsub("\\*{3}.*$", "", gsub("\\*{3}.*?\\*{3}", "", foostring)) 
#> [1] "First test "                      "Second test  something different"
#> [3] "Third test  something different " "Fourth test _something different"
1 Answers

You can use

gsub("\\*{3}.*?(?:\\*{3}|$)", "",  foostring)

See the R online demo

The TRE regex means:

  • \*{3} - three asterisks
  • .*? - any zero or more chars as few as possible
  • (?:\\*{3}|$) - a non-capturing group matching
    • \*{3} - either three asterisks
    • | - or
    • $ - end of string.
Related