繁体   English   中英

R gregexpr上的正则表达式匹配

[英]regex match on R gregexpr

我正在试图计算连续3次“a”事件的实例, "aaa"

该字符串将包含较低的字母,例如"abaaaababaaa"

我尝试了下面这段代码。 但这种行为并不是我想要的。

x<-"abaaaababaaa";
gregexpr("aaa",x);

我希望匹配返回3个“aaa”事件的实例,而不是2。

假设索引从1开始

  • 第一次出现的“aaa”是指数3。
  • 第二次出现的“aaa”是在索引4处。(这不是由gregexpr捕获的)
  • 第三次出现的“aaa”是指数10。

要捕获重叠匹配,您可以使用这样的前瞻:

gregexpr("a(?=aa)", x, perl=TRUE)

但是,您的匹配现在只是一个“a”,因此可能会使这些匹配的进一步处理变得复杂,特别是如果您并不总是寻找固定长度的模式。

我知道我迟到了,但我想分享这个解决方案,

your.string <- "abaaaababaaa"
nc1 <- nchar(your.string)-1
x <- unlist(strsplit(your.string, NULL))
x2 <- c()
for (i in 1:nc1)
x2 <- c(x2, paste(x[i], x[i+1], x[i+2], sep="")) 
cat("ocurrences of <aaa> in <your.string> is,", 
    length(grep("aaa", x2)), "and they are at index", grep("aaa", x2))
> ocurrences of <aaa> in <your.string> is, 3 and they are at index 3 4 10

Fran的R-help得到了这个答案的大力启发。

这是一种使用gregexpr提取不同长度的所有重叠匹配的方法。

x<-"abaaaababaaa"
# nest in lookahead + capture group
# to get all instances of the pattern "(ab)|b"
matches<-gregexpr('(?=((ab)|b))', x, perl=TRUE)
# regmatches will reference the match.length attr. to extract the strings
# so move match length data from 'capture.length' to 'match.length' attr
attr(matches[[1]], 'match.length') <- as.vector(attr(matches[[1]], 'capture.length')[,1])
# extract substrings
regmatches(x, matches)
# [[1]]
# [1] "ab" "b"  "ab" "b"  "ab" "b" 

诀窍是在捕获组中包围模式,并在先行断言中捕获组。 gregexpr将返回一个包含起始位置的列表,其属性为capture.length ,这是一个矩阵,其中第一列是第一个捕获组的匹配长度。 如果将其转换为向量并将其移动到match.length属性(全部为零,因为整个模式位于前瞻断言中),您可以将其传递给regmatches以提取字符串。

正如最终结果的类型暗示的那样,通过一些修改,这可以被矢量化,对于x是字符串列表的情况。

x<-list(s1="abaaaababaaa", s2="ab")
matches<-gregexpr('(?=((ab)|b))', x, perl=TRUE)
# make a function that replaces match.length attr with capture.length
set.match.length<-
function(x) structure(x, match.length=as.vector(attr(x, 'capture.length')[,1]))
# set match.length to capture.length for each match object
matches<-lapply(matches, set.match.length)
# extract substrings
mapply(regmatches, x, lapply(matches, list))
# $s1
# [1] "ab" "b"  "ab" "b"  "ab" "b" 
# 
# $s2
# [1] "ab" "b" 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM