匹配R中的整个字符串

时间:2013-11-26 16:49:08

标签: regex r gsub

考虑以下字符串:

string = "I have #1 file and #11 folders"

我想将模式#1替换为one,但我不想修改#11。结果应该是:

string = "I have one file and #11 folders"

我试过了:

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

但这取代了#1和#11。我也尝试过:

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

但是这并没有取代任何东西,因为模式是包含空格的字符串的一部分。

请注意,如果初始字符串如下所示:

string = "I have #1 file blah blah blah and #11 folders"

我希望结果是:

string = "I have 1 file blah blah blah and #11 folders"

换句话说,我真的只想更改确切的模式#1而不触及字符串的其余部分。这可能吗?

3 个答案:

答案 0 :(得分:4)

我不确定我是否理解正确,但这有帮助 -

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"

答案 1 :(得分:3)

如果对perl=TRUE之类的工具使用gsub参数,那么将使用perl regex引擎,它有一些可能有用的选项。

模式“#1 \\ b”将匹配#1后跟字边界,因此它将匹配#1,但不匹配#11(因为2 1之间没有边界)。还有一些正面和负面的工具可以查找模式后面的内容(比如文件可能),但不包含在要替换的部分中。

答案 2 :(得分:1)

使用#1之后的空格:

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

[1] "I have one file and #11 folders"