加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

R中的正则表达式 – 以“OR”方式组合两种模式.无法发现错误.

发布时间:2020-12-14 05:36:58 所属栏目:百科 来源:网络整理
导读:我想在vec中找到pat1或pat2 vec - c("(and) i.e.","(and) ie","(and)ie","and i.e.","and ie","and) i.e.")pat1 - "(and) i.e."pat2 - "(and) ie" 我尝试使用(pat1 | pat2)组合这两个模式 # combine the two patterns pat1or2 - paste0("(",pat1,"|"
我想在vec中找到pat1或pat2

vec <- c("(and) i.e.","(and) ie","(and)ie","and i.e.","and ie","and) i.e.")

pat1 <- "(and) i.e."
pat2 <- "(and) ie"

我尝试使用(pat1 | pat2)组合这两个模式

# combine the two patterns 
pat1or2 <- paste0("(",pat1,"|",pat2,")")
# [1] "((and) i.e.|(and) ie)"

grep(pat1,vec,value=TRUE)
# [1] "(and) i.e."

grep(pat2,value=TRUE)
# [1] "(and) ie"

grep(pat1or2,value=TRUE)
# character(0)

显然,我错过了一些东西,我无法发现它.
(尝试弄乱perl并修复,但那不是)

你能指出我在组合这两种模式时的错误吗?

解决方法

你忘了反驳所有的括号.你的两种模式应该是:

pat1 <- "(and) i.e."
pat2 <- "(and) ie"

在那之后,一切都应该没问题,有或没有perl = TRUE.什么可能让你找到错误的正确使用perl = TRUE与你的旧(错误)模式:

grep(pat1,value=TRUE,perl = TRUE)
# Error in grep(pat1,value = TRUE,perl = TRUE) : 
#   invalid regular expression '(and) i.e.'

说清楚你有不平衡的括号.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读