string 从字符串中删除括号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9449466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:23:36  来源:igfitidea点击:

remove parenthesis from string

stringrgrepsubstring

提问by mike

I am trying to remove a parenthesis from a string in R and run into the following error:

我试图从 R 中的字符串中删除括号并遇到以下错误:

string <- "log(M)"
gsub("log", "", string) # Works just fine
gsub("log(", "", string) #breaks
# Error in gsub("log(", "", test) : 
#   invalid regular expression 'log(', reason 'Missing ')''

回答by Ben Bolker

Escape the parenthesis with a double-backslash:

用双反斜杠转义括号:

gsub("log\(", "", string)

(Obligatory: http://xkcd.com/234/)

(强制性:http: //xkcd.com/234/

回答by Josh O'Brien

Ben's answer gives you the good generally applicable way of doing this.

Ben 的回答为您提供了普遍适用的方法。

Alternatively, in your situation you could use the fixed=TRUEargument, like this:

或者,在您的情况下,您可以使用该fixed=TRUE参数,如下所示:

gsub("log(", "", string, fixed=TRUE)
# [1] "M)"

It is appropriate whenever the patternargument to gsub()is a character string containing the literal sequence of characters you are searching for. Then, it's nice because it allows you to type the exact pattern that you are searching for, without escapes etc.

只要patternto的参数gsub()是包含您要搜索的字面量字符序列的字符串,就很合适。然后,这很好,因为它允许您键入您正在搜索的确切模式,而无需转义等。