簡體   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