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
remove parenthesis from string
提问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=TRUE
argument, like this:
或者,在您的情况下,您可以使用该fixed=TRUE
参数,如下所示:
gsub("log(", "", string, fixed=TRUE)
# [1] "M)"
It is appropriate whenever the pattern
argument 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.
只要pattern
to的参数gsub()
是包含您要搜索的字面量字符序列的字符串,就很合适。然后,这很好,因为它允许您键入您正在搜索的确切模式,而无需转义等。