为什么我的正则表达式不能在R中与grep一起工作?

vqlkdk9b  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(69)

我试着在regex101.com中编写代码来识别任何类型的电子邮件地址。
一般的电子邮件地址格式是这样的:
[[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)
[[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)
[[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection)
如果我只想在文本中选择电子邮件,此命令在www.regex101.com中有效。regex101.com链接如下:https://regex101.com/r/UA6CTA/1

(\w){1,25}(.|\w){1,25}@(\w){1,25}.(\w){1,25}(.|\w|$)((\w){1,25}|$)

字符串
但是当我在R中编写这个脚本时,即使我使用\instead\和grep命令,它也会给我“字符(0)"。脚本如下:

emails <- c("[email protected]",
"[email protected]",
"[email protected]",
"invalid.edu",
"[email protected]",
"[email protected]")
emails[grep(pattern = r"(\w){1,25}(.|\w){1,25}@(\w){1,25}.(\w){1,25}(.|\w|$)((\w){1,25}|$)",
x=emails)]


端子中的输出如下:

emails[grep(pattern = r"((\w){1,25}(.|\w){1,25}@(\w){1,25}.
+             (\w){1,25}(.|\w|$)((\w){1,25}|$))",
+             x=emails)]
character(0)


有人能帮我做什么吗?

ux6nzvsh

ux6nzvsh1#

我假设regex 101中使用的正则表达式没有双反斜杠,如下所示:

(\w){1,25}(.|\w){1,25}@(\w){1,25}.(\w){1,25}(.|\w|$)((\w){1,25}|$)

字符串
尽管这与R示例中的不匹配,也没有额外的转义。此外,R示例中的正则表达式被标记为原始字符串(r"..."),但在R中也应该使用开始和结束序列(即r"(...)",更多细节在R帮助中,?Quotes)。

emails <- c("[email protected]",
             "[email protected]",
             "[email protected]",
             "invalid.edu",
             "[email protected]",
             "[email protected]")

emails[grep(pattern=r"((\w){1,25}(.|\w){1,25}@(\w){1,25}.(\w){1,25}(.|\w|$)((\w){1,25}|$))", ,x=emails)]
#> [1] "[email protected]"     "[email protected]"       
#> [3] "[email protected]"     "[email protected]"       
#> [5] "[email protected]"


或者没有原始字符串:

emails[grep(pattern="(\\w){1,25}(.|\\w){1,25}@(\\w){1,25}.(\\w){1,25}(.|\\w|$)((\\w){1,25}|$)", x=emails)]
#> [1] "[email protected]"     "[email protected]"       
#> [3] "[email protected]"     "[email protected]"       
#> [5] "[email protected]"


创建于2023-01-28带有reprex v2.0.2

x6yk4ghg

x6yk4ghg2#

这是令人难以置信的。但关键点是,当你使用regex by grep作为一个刺,如果在pattern=“bla bla bla.”之后,你去下一行,因为R保证金,它改变了字符串的形式。在下面我描述的解决方案。
例如,我想保存字符串“Hello to programming lovers”到一个字符串变量。

st<- "Hello to programming lovers"
st

字符串
输出:

[1] "Hello to programming lovers"


现在,出于任何原因,我重复上述代码在2行,而不是一行。

st<- "Hello to 
programming lovers"
st


输出:

[1] "Hello to \n    programming lovers"


这是很自然的,当我用两行代码写这段代码时,它给了我“字符(0)"。

`emails[grep(pattern =r"((\w){1,25}(\.|\w){0,25}
        (\w){1,25}@(\w){1,25}\.(\w){1,25}(\.|\w|$)((\w){1,25}|$))",x=emails)]


输出:

character(0)

同时,当你只在一行中使用它或与“paste”命令一起使用sep="”时,它会给你想要的结果。
这很简单,但ticky!

相关问题