匹配R中的整个字符串 [英] Matching entire string in R

查看:126
本文介绍了匹配R中的整个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下字符串:

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

我想用词one替换模式#1,但是我不想修改#11.结果应该是:

I would like to replace the pattern #1 with the word one, but I don't want to modify th #11. The result should be:

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

我尝试过:

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

但是这同时替换了#1和#11.我也尝试过:

but this replaces both #1 and #11. I have also tried:

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

但这不会替代任何内容,因为该模式是包含空格的字符串的一部分.

but this doesn't replace anything since the pattern is part of a string that contains spaces.

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

Please note that if the initial string looked like:

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

我希望结果是:

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

换句话说,我实际上只是想更改确切的模式#1而不接触字符串的其余部分.有可能吗?

In other words, I literally just want to change the exact pattern #1 without touching the rest of the string. Is that possible?

推荐答案

如果对gsub之类的工具使用perl=TRUE自变量,则将使用perl regex引擎,该引擎具有一些可能有用的选项.

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.

模式#1 \\ b"将匹配#1,后跟一个单词边界,因此它将匹配#1,但不匹配#11(因为2 1之间没有边界).还有一些用于正面和负面展望的工具,可以根据您的模式(例如单词文件)查找内容,但不包含在要替换的部分中.

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.

这篇关于匹配R中的整个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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