正则表达式匹配字符串中重复两次的前几个字符
Regular expression to match first few characters repeated twice in string
我遇到了一个问题,要查找所有具有 前几个 (>=2) 个字符 重复 两次 的字符串R语言.
例如
字符串应该select出
(1) allochirally ------> 前3个字符'all'在string[=38=中重复了两次]
(2) froufrou ------> 前 4 个字符 'frou' 在字符串中重复两次
(3) undergrounder ------> 前5个字符'under'在字符串
中重复了两次
字符串应该不 select出
(1) gummage ------> even first character 'g' 重复两次,但只有1个字符,不符合条件 >=2 first characters
(2) hypergoddess ------> 没有前几个字符重复两次
(3) kgashga ------> even 'ga' 重复两次,但不包含第一个字符 'k',不匹配需要包含第一个字符的条件
听说 backreference
(例如 \b 或 \w)可能会有帮助,但仍然无法弄清楚,你能帮忙弄清楚吗?
注意:我看到有一个函数作为 xmatch <- str_extract_all(x, regex) == x
作为方法使用,str_extract_all
来自 library(stringr)
x <- c("allochirally", "froufrou", "undergrounder", "gummage", "hypergoddess", "kgashga")
regex <- "as described details here"
function(x, regex) {
xmatch <- str_extract_all(x, regex) == x
matched_x <- x[xmatch]
}
如果很简洁会更喜欢!!谢谢
使用grepl
:
x <- c("allochirally", "froufrou", "undergrounder", "gummage", "hypergoddess", "kgashga")
grepl("^(.{2,}).*\1.*$", x)
[1] TRUE TRUE TRUE FALSE FALSE FALSE
正则表达式模式匹配并捕获前两个或更多字符,然后还断言相同的两个或更多字符出现在字符串的后面。
如果您想使用我的答案中的逻辑来获得匹配字符串的向量,那么只需使用:
x[grepl("^(.{2,}).*\1.*$", x)]
[1] "allochirally" "froufrou" "undergrounder"
怎么样:
^(\w{2,}).*?.*?$
如所见here
解释:
第一个捕获组(\w{2,})
匹配前几个字符,反向引用
指向这个捕获组
如果以后需要,可以参考group(1)
中重复的字符部分
我遇到了一个问题,要查找所有具有 前几个 (>=2) 个字符 重复 两次 的字符串R语言.
例如
字符串应该select出
(1) allochirally ------> 前3个字符'all'在string[=38=中重复了两次]
(2) froufrou ------> 前 4 个字符 'frou' 在字符串中重复两次
(3) undergrounder ------> 前5个字符'under'在字符串
字符串应该不 select出
(1) gummage ------> even first character 'g' 重复两次,但只有1个字符,不符合条件 >=2 first characters
(2) hypergoddess ------> 没有前几个字符重复两次
(3) kgashga ------> even 'ga' 重复两次,但不包含第一个字符 'k',不匹配需要包含第一个字符的条件
听说 backreference
(例如 \b 或 \w)可能会有帮助,但仍然无法弄清楚,你能帮忙弄清楚吗?
注意:我看到有一个函数作为 xmatch <- str_extract_all(x, regex) == x
作为方法使用,str_extract_all
来自 library(stringr)
x <- c("allochirally", "froufrou", "undergrounder", "gummage", "hypergoddess", "kgashga")
regex <- "as described details here"
function(x, regex) {
xmatch <- str_extract_all(x, regex) == x
matched_x <- x[xmatch]
}
如果很简洁会更喜欢!!谢谢
使用grepl
:
x <- c("allochirally", "froufrou", "undergrounder", "gummage", "hypergoddess", "kgashga")
grepl("^(.{2,}).*\1.*$", x)
[1] TRUE TRUE TRUE FALSE FALSE FALSE
正则表达式模式匹配并捕获前两个或更多字符,然后还断言相同的两个或更多字符出现在字符串的后面。
如果您想使用我的答案中的逻辑来获得匹配字符串的向量,那么只需使用:
x[grepl("^(.{2,}).*\1.*$", x)]
[1] "allochirally" "froufrou" "undergrounder"
怎么样:
^(\w{2,}).*?.*?$
如所见here
解释:
第一个捕获组(\w{2,})
匹配前几个字符,反向引用指向这个捕获组
如果以后需要,可以参考group(1)
中重复的字符部分