在r中使用gsub删除模式 [英] Removing a pattern With gsub in r

查看:135
本文介绍了在r中使用gsub删除模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串Project Change Request (PCR) - HONDA DIGITAL PLATEFORM保存在supp_matches中,并且supp_matches1包含字符串Project Change Request (PCR) -.

I have a string Project Change Request (PCR) - HONDA DIGITAL PLATEFORM saved in supp_matches, and supp_matches1 contains the string Project Change Request (PCR) -.

supp_matches2 <- gsub("^.*[supp_matches1]","",supp_matches)
supp_matches2
# [1] " (PCR) - HONDA DIGITAL PLATEFORM"

这实际上是不正确的,但应该是这样

Which is actually not correct but it should come like

supp_matches2
# [1] "HONDA DIGITAL PLATEFORM"

为什么它没有达到应有的状态?

Why is it not coming the way it should be?

推荐答案

正如我在评论中所说,在您的表达式gsub("^.*[supp_matches1]", "", supp_matches)中,您实际上并没有使用对象supp_matches1,而只是使用其中的字母.

As I say in my comment, in your expression gsub("^.*[supp_matches1]", "", supp_matches), you're not really using the object supp_matches1 but just the letters inside it.

您可以执行gsub(paste0("^.*", supp_matches1), "", supp_matches)之类的操作来真正使用supp_matches1中包含的表达式,除了@rawr提到的那样,表达式中带有括号,因此您需要对它们进行排除.
得到您想要的东西的正确表达式将是sub("Project Change Request \\(PCR\\) - ", "", supp_matches)

You could do something like gsub(paste0("^.*", supp_matches1), "", supp_matches) to really use the expression contained in supp_matches1, except that, as mentionned by @rawr, you have parentheses in your expression so you would need to excape them.
The correct expression to get what you want would then be sub("Project Change Request \\(PCR\\) - ", "", supp_matches)

要获得所需的内容,可以使用gsub(sub)函数的fixed参数,这表示参数pattern中的表达式将按原样进行匹配(因此,不带需要转义任何内容,而且也不需要真正的正则表达式.

To get what you want, you can use the fixed parameter of gsub (sub) function, which is saying that the expression in the parameter pattern will be matched as it is (so, without the need to escape anything, but also, no real regular expression).

所以您正在寻找的是:

gsub(supp_matches1, "", supp_matches, fixed=TRUE) # or just with `sub` in this case
#[1] "HONDA DIGITAL PLATEFORM"

这篇关于在r中使用gsub删除模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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