Matching entire string in R

夙愿已清 提交于 2019-12-02 03:46:01

If you use the perl=TRUE argument to tools like gsub then the perl regex engine will be used which has some options that could help.

The pattern "#1\\b" will match #1 followed by a word boundary, so it would match #1, but not #11 (since there is no boundary between the 2 1's). There are also tools for positive and negative look ahead which look for things following your pattern (like the word file maybe), but does not include them in the part to be replaced.

I'm not sure if I understood right, but does this help -

a <- "I have #1 file and #11 folders"
b <- "I have #1file and #11 folders"
c <- "I have #1,file and #11 folders"

> gsub(x = a, pattern = "#1.*file", replacement = "one file")
[1] "I have one file and #11 folders"
> gsub(x = b, pattern = "#1.*file", replacement = "one file")
[1] "I have one file and #11 folders"
> gsub(x = c, pattern = "#1.*file", replacement = "one file")
[1] "I have one file and #11 folders"

Use the space after #1 to your advantage:

gsub("#1 ", "one ", string, fixed = TRUE)

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