簡體   English   中英

R:環顧四周

[英]R: lookaround within lookaround

我需要匹配前面有兩個不同元音的'r'。 例如,'我們'或'梨'將匹配,但'bar'或'aar'不匹配。 我確實設法匹配兩個不同的元音,但我仍然不能使后續'r'的后視條件( ... )。 既不是(?<=...)r也不是...\\\\Kr產生任何結果。 有任何想法嗎?

x <- c('([aeiou])(?!\\1)(?=(?1))')
y <- c('our','pear','bar','aar')
y[grepl(paste0(x,collapse=''),y,perl=T)]
## [1] "our"  "pear"`

這兩個解決方案似乎有效:

為什么不這樣:

x <- '(?<=a[eiou]|e[aiou]|i[aeou]|o[aeiu]|u[aeio])r'
y[grepl(x, y, perl=T)]

\\K方式:

x <- '([aeiou])(?!\\1)[aeiou]\\Kr'
y[grepl(x, y, perl=T)]

為什么不是方式變體(可能更有效,因為它之前搜索“r”):

x <- 'r(?<=a[eiou]r|e[aiou]r|i[aeou]r|o[aeiu]r|u[aeio]r)'

或快速排除“r”之前沒有兩個元音(不測試整個交替)

x <- 'r(?<=[aeiou][aeiou]r)(?<=a[eiou]r|e[aiou]r|i[aeou]r|o[aeiu]r|u[aeio]r)'

正如HamZa在評論中指出的,使用跳過和失敗動詞是我們想要的一種方式。 基本上我們告訴它忽略我們有兩個相同的元音后跟“r”的情況

# The following is the beginning of the regex and isn't just R code
# the ([aeiou]) captures the first vowel, the \\1 references what we captured
# so this gives us the same vowel two times in a row
# which we then follow with an "r"
# Then we tell it to skip/fail for this
([aeiou])\\1r(*SKIP)(*FAIL)

現在我們告訴它跳過這些情況,所以現在我們告訴它“或者我們有兩個元音后跟'r'的情況”,因為我們已經消除了這兩個元音相同的情況,這將得到我們想要的東西。

|[aeiou]{2}r

把它放在一起我們最終得到了

y <- c('our','pear','bar','aar', "aa", "ae", "are", "aeer", "ssseiras")
grep("([aeiou])\\1r(*SKIP)(*FAIL)|[aeiou]{2}r", y, perl = TRUE, value = TRUE)
#[1] "our"    "pear"    "sseiras"

這是一個不太優雅的解決方案:

y[grepl("[aeiou]{2}r", y, perl=T) & !grepl("(.)\\1r", y, perl=T)]

可能有一些角落案例失敗,其中第一組在不同位置匹配而不是第二組(將不得不考慮這一點),但有些東西可以讓你開始。

另一個通過否定先行斷言。

> y <- c('our','pear','bar','aar', "aa", "ae", "are", "aeer", "ssseiras")
> grep("(?!(?:aa|ee|ii|oo|uu)r)[aeiou][aeiou]r", y, perl=TRUE, value=TRUE)
[1] "our"      "pear"     "ssseiras"

> grep("(?!aa|ee|ii|oo|uu)[aeiou][aeiou]r", y, perl=TRUE, value=TRUE)
[1] "our"      "pear"     "ssseiras"

(?!aa|ee|ii|oo|uu)斷言匹配中的前兩個字符不是aaee或....或uu 所以這個[aeiou][aeiou]會匹配任何兩個元音,但不會重復。 這就是我們首先設定條件的原因。 r匹配元音后面的r。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM