是否有一个R函数来转义正则表达式字符的字符串

前端之家收集整理的这篇文章主要介绍了是否有一个R函数来转义正则表达式字符的字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要构建一个正则表达式替换一些字符串来搜索,所以这些字符串需要转义,然后才能将它们放在正则表达式中,这样,如果搜索的字符串包含正则表达式字符,它仍然可以工作.

某些语言具有这样的功能(例如python re.escape:https://stackoverflow.com/a/10013356/1900520). R有这样的功能吗?

例如(组成功能):

x = "foo[bar]"
y = escape(x) # y should now be "foo\\[bar\\]"
我写了一个R版本的Perl的quoteMeta功能
library(stringr)
quoteMeta <- function(string) {
  str_replace_all(string,"(\\W)","\\\\\\1")
}

我总是使用正则表达式的perl风格,所以这对我有用.我不知道它是否适用于R中的“正常”正则表达式.

编辑:我找到了解释为什么这个工作的来源.这是在Quoting Metacharacters section of the perlre manpage

This was once used in a common idiom to disable or quote the special meanings of regular expression Metacharacters in a string that you want to use for a pattern. Simply quote all non-“word” characters:

06001

正如你所看到的,上面的R代码是直接翻译这个相同的替代(在通过反斜杠地狱之后).联机帮助页也说(强调我的):

Unlike some other regular expression languages,there are no backslashed symbols that aren’t alphanumeric.

这加强了我的观点,即该解决方案仅保证PCRE.

原文链接:https://www.f2er.com/regex/357056.html

猜你在找的正则表达式相关文章