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

标签 regex string 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:

$pattern =~ s/(\W)/\\$1/g;


如您所见,上面的 R 代码是对相同替换的直接翻译(在经历了反斜杠 hell 之后)。联机帮助页还说(强调我的):

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



这加强了我的观点,即该解决方案仅适用于 PCRE。

关于regex - 是否有 R 函数来转义正则表达式字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14836754/

相关文章:

regex - 使用 sed 和正则表达式解析无线调查的 iwlist 命令输出

java - 从 tcpflow 输出格式化 IP?

c# - 获取两个字符串的公共(public)前缀

R:如何根据因子水平计算差异?

R中的旋转 Axis 标签

r - 如何解决 R 中 Sankey 的未定义列错误?

javascript - 将输入值与 Javascript 中的正则表达式匹配

javascript - 正则表达式第一次出现

python域名拆分名称和扩展名

无法正确解码多项式