为什么R(至少与tidyverse / stringr)识别以下正则表达式:*\.(png|jpg|jpeg)
?(在 R 中,由于字符转义,实际上需要编写字符串"*\\.(png|jpg|jpeg)"
)
我认为正确的正则表达式应该是.*\.(png|jpg|jpeg)
(用 R 编写".*\\.(png|jpg|jpeg)"
))
当我在例如 regex101.com 上介绍第一个表达式时,它说这是一个非法的正则表达式。但是 R 似乎可以毫无问题地解析它。
为什么?
该表达式是否*\.(png|jpg|jpeg)
为有效的正则表达式?如果是这样,为什么 regex101 会抱怨?如果没有,为什么 R 接受它?
如果您将基本 R 正则表达式函数与默认 TRE 正则表达式库一起使用,*
则模式开头的 将被忽略。它与基于 POSIX 的正则表达式引擎的行为方式一致,请参阅此sed
演示(此工具在演示中使用 POSIX BRE)。
TRE 正则表达式引擎是基于 POSIX 的正则表达式引擎,它会忽略正则表达式*
开头的 :
> gsub("*\\.png$", "", "abc.png")
[1] "abc"
但是,其他 NFA 正则表达式引擎将其视为错误:
> library(stringr)
> str_replace("abc.png", "*\\.png$", "")
Error in stri_replace_first_regex(string, pattern, fix_replacement(replacement), :
Syntax error in regexp pattern. (U_REGEX_RULE_SYNTAX, context=`*\.png$`)
> gsub("*\\.png$", "", "abc.png", perl=TRUE)
Error in gsub("*\\.png$", "", "abc.png", perl = TRUE) :
invalid regular expression '*\.png$'
In addition: Warning message:
In gsub("*\\.png$", "", "abc.png", perl = TRUE) :
PCRE pattern compilation error
'quantifier does not follow a repeatable item'
at '*\.png$'
stringr
regex 函数使用ICU regex 库和基本 R regex 函数并perl=TRUE
使用PCRE regex 库(不是perl
!)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句