Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何防止regmatches删除非匹配项?_Regex_R - Fatal编程技术网

Regex 如何防止regmatches删除非匹配项?

Regex 如何防止regmatches删除非匹配项?,regex,r,Regex,R,我想捕获第一个匹配项,如果没有匹配项,则返回NA 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"

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

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"
regexpr(“a+”,c(“abc”,“def”,“cba”,“aa”),perl=TRUE)
# [1]  1 -1  3  1
#属性(,“匹配长度”)
# [1]  1 -1  1  2

x改用
regexec
,因为它返回一个列表,允许您在
取消列表之前捕获
字符(0)

 R <- regmatches(x, regexec("a+", x))
 unlist({R[sapply(R, length)==0] <- NA; R})

 # [1] "a"  NA   "a"  "aa"

R使用或多或少与您相同的结构-

chars <- c("abc", "def", "cba a", "aa")    

chars[
   regexpr("a+", chars, perl=TRUE) > 0
][1] #abc

chars[
   regexpr("q", chars, perl=TRUE) > 0
][1]  #NA

#vector[
#    find all indices where regexpr returned positive value i.e., match was found
#][return the first element of the above subset]
chars 0
][1] #abc
查尔斯[
regexpr(“q”,chars,perl=TRUE)>0
][1] #那
#载体[
#查找regexpr返回正值的所有索引,即找到匹配项
#][返回上述子集的第一个元素]

编辑-似乎我误解了这个问题。但既然有两个人发现这很有用,我就让它留在这里。

继续使用
regexpr

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

r在r3.3.0中,可以使用invert=NA参数提取匹配结果和非匹配结果。从帮助文件中,它说

如果invert为NA,则regmatches同时提取非匹配和匹配的子字符串,始终以非匹配开头和结尾(如果匹配分别发生在开头或结尾,则为空)

输出是一个列表,通常在大多数情况下,(匹配单个模式),
regmatches
使用此参数将返回一个长度为3或1的元素列表。1表示未找到匹配项,3表示存在匹配项

myMatch <- regmatches(x, m, invert=NA)
myMatch
[[1]]
[1] ""   "a"  "bc"

[[2]]
[1] "def"

[[3]]
[1] "cb" "a"  " a"

[[4]]
[1] ""   "aa" ""
此时,如果您真的想要NA而不是“”,可以使用

is.na(myVec) <- nchar(myVec) == 0L
myVec
[1] "a"  NA   "a"  "aa"
因此,您可以在一行相当可读的文字中完成整个工作:

myVec <- sapply(myMatch, function(x) {if(length(x) == 1) NA_character_ else x[2]})
sapply(regmatches(x, m, invert=NA), `[`, 2)

我想约翰的观点(暗示)是,这并不完全符合OP的要求。我以为你想要的是第一场比赛或NA,而不是别的什么?似乎有些混乱。这说明了在提出问题时需要更高的精度,最好是要求准确的输出。
unlist({R[length(R)==0]
sapply(myMatch, `[`, 2)
[1] "a"  NA   "a"  "aa"
sapply(regmatches(x, m, invert=NA), `[`, 2)