Removing/replacing brackets from R string using gsub

萝らか妹 提交于 2020-01-02 05:58:16

问题


I want to remove or replace brackets "(" or ")" from my string using gsub. However as shown below it is not working. What could be the reason?

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

回答1:


Using the correct regex works:

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

The additional square brackets mean "match any of the characters inside".




回答2:


The possible way could be (in the line OP is trying) as:

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


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



回答3:


Or 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"


来源:https://stackoverflow.com/questions/49681952/removing-replacing-brackets-from-r-string-using-gsub

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!