str_replace (package stringr) 不能替换 r 中的括号? [英] str_replace (package stringr) cannot replace brackets in r?

查看:57
本文介绍了str_replace (package stringr) 不能替换 r 中的括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,比如说

I have a string, say

 fruit <- "()goodapple"

我想删除字符串中的括号.我决定使用 stringr 包,因为它通常可以处理此类问题.我使用:

I want to remove the brackets in the string. I decide to use stringr package because it usually can handle this kind of issues. I use :

str_replace(fruit,"()","")

但是什么都没有替换,下面替换了:

But nothing is replaced, and the following is replaced:

[1] "()good"

如果我只想更换右半括号,它可以工作:

If I only want to replace the right half bracket, it works:

str_replace(fruit,")","") 
[1] "(good"

然而,左半括号不起作用:

However, the left half bracket does not work:

str_replace(fruit,"(","")

并显示以下错误:

Error in sub("(", "", "()good", fixed = FALSE, ignore.case = FALSE, perl = FALSE) : 
 invalid regular expression '(', reason 'Missing ')''

有人知道为什么会发生这种情况吗?那么如何删除字符串中的()"呢?

Anyone has ideas why this happens? How can I remove the "()" in the string, then?

推荐答案

转义括号可以...

str_replace(fruit,"\\(\\)","")
# [1] "goodapple"

<小时>

您可能还想考虑探索 "stringi" 包,与"stringr"有类似的做法,但功能更灵活.例如,有 stri_replace_all_fixed,它在这里很有用,因为您的搜索字符串是固定模式,而不是正则表达式模式:


You may also want to consider exploring the "stringi" package, which has a similar approach to "stringr" but has more flexible functions. For instance, there is stri_replace_all_fixed, which would be useful here since your search string is a fixed pattern, not a regex pattern:

library(stringi)
stri_replace_all_fixed(fruit, "()", "")
# [1] "goodapple"

<小时>

当然,基本的 gsub 也能很好地处理这个:


Of course, basic gsub handles this just fine too:

gsub("()", "", fruit, fixed=TRUE)
# [1] "goodapple"

这篇关于str_replace (package stringr) 不能替换 r 中的括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆