Delete part between brackets in a string when it occurs at the end of the string in R using gsub

StackOverflow https://stackoverflow.com/questions/20926708

  •  24-09-2022
  •  | 
  •  

Вопрос

I am on the lookout for a gsub expression that would delete any part of a string between brackets, but only when it occurs at the end of that string. E.g. for

string="n-Pentacosane (C-25)"

I would like it to return just "n-Pentacosane". Important though is that it wouldn't delete anyting written between brackets earlier on in the string. Anybody any thoughts perhaps?

Это было полезно?

Решение

This should do it:

sub(' *\\([^)]*)$', '', "n-Pentacosane (C-25)")

That is:

  • sub is enough, because we will do a single replacement
  • To match the starting bracket we need to write: \\(. No need to escape the second.
  • To match at the end, we need two things:
    1. match at the end using $
    2. make the matching non-greedy: by using [^)]* we avoid replacing too much in input like penta (something) cosane (C-25), to get penta (something) cosane as result instead of penta
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top