Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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
R gregexpr上的正则表达式匹配_Regex_String_R - Fatal编程技术网

R gregexpr上的正则表达式匹配

R gregexpr上的正则表达式匹配,regex,string,r,Regex,String,R,我正在尝试计数3个连续的“a”事件的实例,“aaa” 字符串将包含较低的字母表,例如“abaabaaa” 我尝试了下面的代码。但这种行为并不是我想要的 x<-"abaaaababaaa"; gregexpr("aaa",x); x要捕获重叠匹配,可以使用如下前瞻: gregexpr("a(?=aa)", x, perl=TRUE) 但是,您的匹配现在只是一个“a”,因此可能会使这些匹配的进一步处理复杂化,特别是如果您不总是寻找固定长度的模式。我知道我迟到了,但我想分享这个解决方案 yo

我正在尝试计数3个连续的“a”事件的实例,
“aaa”

字符串将包含较低的字母表,例如
“abaabaaa”

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

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

x要捕获重叠匹配,可以使用如下前瞻:

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

your.string下面是一种使用
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" 

这项工作也可以(投票赞成),但我想避免显式循环,我的字符串很长。@AdityaSihag,它肯定可以优化,我只是想把这个解决方案也放在那里。
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"