[英]regex to replace words with more than two consecutive characters
如何檢測一個單詞中存在兩個以上連續字符並刪除該單詞?
我似乎能夠做到這一點:
# example data
mystring <- c(1, 2, 3, "toot", "tooooot")
# clunky regex
gsub("^[[:alpha:]]$", "", gsub(".*(.)\\1+\\1", "", mystring))
[1] "1" "2" "3" "toot" ""
但我敢肯定,有一種更有效的方法。 我只用一個gsub
怎么做?
像這樣組合表達式:
gsub("^[[:alpha:]]*([[:alpha:]])\\1\\1[[:alpha:]]*$", "", mystring)
您可以改用grepl
。
mystring <- c(1, 2, 3, "toot", "tooooot", "good", "apple", "banana")
mystring[!grepl("(.)\\1{2,}", mystring)]
## [1] "1" "2" "3" "toot" "good" "apple" "banana"
**說明**
\\\\1
匹配第一個組(在這種情況下為(.)
)。 {2,}
指定前面的字符至少應匹配2次或更多次。 由於我們要匹配重復3次或更多次的任何字符-第一次出現(.)
,因此\\\\1
需要匹配2次或更多次。
另一種可能性:
mystring[grepl("(.{1})\\1{2,}", mystring, perl=T)] <- ""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.