简体   繁体   English

使用 gsub 从 R 字符串中删除/替换括号

[英]Removing/replacing brackets from R string using gsub

I want to remove or replace brackets "(" or ")" from my string using gsub.我想使用 gsub 从我的字符串中删除或替换括号“(”或“)”。 However as shown below it is not working.但是,如下所示,它不起作用。 What could be the reason?可能是什么原因?

 >  k<-"(abc)"
 >  t<-gsub("()","",k)
 >  t 
[1] "(abc)"

Using the correct regex works:使用正确的正则表达式有效:

gsub("[()]", "", "(abc)")

The additional square brackets mean "match any of the characters inside" .额外的方括号表示“匹配里面的任何字符”

A safe and simple solution that doesn't rely on regex:一个不依赖于正则表达式的安全简单的解决方案:

k <- gsub("(", "", k, fixed = TRUE) # "Fixed = TRUE" disables regex
k <- gsub(")", "", k, fixed = TRUE)
k
[1] "abc"

The possible way could be (in the line OP is trying) as:可能的方法可能是(在 OP 正在尝试的行中)为:

gsub("\\(|)","","(abc)")
#[1] "abc"


`\(`  => look for `(` character. `\` is needed as `(` a special character. 
`|`  =>  OR condition 
`)` =   Look for `)`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM