如何防止regmatchs丢弃非匹配项? [英] How to prevent regmatches drop non matches?

查看:19
本文介绍了如何防止regmatchs丢弃非匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕获第一个匹配项,如果没有匹配项,则返回 NA.

I would like to capture the first match, and return NA if there is no match.

regexpr("a+", c("abc", "def", "cba a", "aa"), perl=TRUE)
# [1]  1 -1  3  1
# attr(,"match.length")
# [1]  1 -1  1  2

x <- c("abc", "def", "cba a", "aa")
m <- regexpr("a+", x, perl=TRUE)
regmatches(x, m)
# [1]  "a"  "a"  "aa"

所以我期望 "a", NA, "a", "aa"

So I expected "a", NA, "a", "aa"

推荐答案

继续使用 regexpr:

r <- regexpr("a+", x)
out <- rep(NA,length(x))
out[r!=-1] <- regmatches(x, r)
out
#[1] "a"  NA   "a"  "aa"

这篇关于如何防止regmatchs丢弃非匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆