Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 使用gsub删除字符串中括号之间的部分,该部分出现在R中字符串的末尾_Regex_R_Replace_Gsub - Fatal编程技术网

Regex 使用gsub删除字符串中括号之间的部分,该部分出现在R中字符串的末尾

Regex 使用gsub删除字符串中括号之间的部分,该部分出现在R中字符串的末尾,regex,r,replace,gsub,Regex,R,Replace,Gsub,我正在寻找一个gsub表达式,它可以删除括号中字符串的任何部分,但只有当它出现在该字符串的末尾时才会删除。例如,为了 string="n-Pentacosane (C-25)" 我希望它只返回“正戊烷”。 但重要的是,它不会删除先前在字符串中括号之间写入的任何内容。有人有什么想法吗?应该这样做: sub(' *\\([^)]*)$', '', "n-Pentacosane (C-25)") 即: sub就足够了,因为我们只做一次更换 为了匹配起始括号,我们需要写:\\(),无需转义第二个括

我正在寻找一个gsub表达式,它可以删除括号中字符串的任何部分,但只有当它出现在该字符串的末尾时才会删除。例如,为了

string="n-Pentacosane (C-25)"
我希望它只返回
“正戊烷”
。 但重要的是,它不会删除先前在字符串中括号之间写入的任何内容。有人有什么想法吗?

应该这样做:

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

  • sub
    就足够了,因为我们只做一次更换
  • 为了匹配起始括号,我们需要写:
    \\(
    ),无需转义第二个括号
  • 为了最终匹配,我们需要两件事:
  • 使用
    $
  • 使匹配非贪婪:通过使用
    [^]*
    我们避免替换太多的输入,如
    penta(something)cosane(C-25)
    ,从而得到
    penta(something)cosane
    ,而不是
    penta

谢谢!我一直在不断地学习(g)sub的百万种可能用法:-)