Regex 第2次出现之间的正则表达式PCRE字符
我有类似以下结构的数据。我需要提取第三次出现“2016年5月”和“2016年6月”之间的数据 我有下面的模式(坦率地说)没有正确构建(并且它没有带回我想要的角色) 我不熟悉使用正则表达式,有人能帮我正确的表达吗 2016年5月ef 2016年6月efef 2016年5月2016年6月2016年5月 dffdg def efef 2016年6月 2016年5月 2016年6月 如果假设“2016年5月”和“2016年6月”交替出现,且前者先出现,则Regex 第2次出现之间的正则表达式PCRE字符,regex,r,pcre,Regex,R,Pcre,我有类似以下结构的数据。我需要提取第三次出现“2016年5月”和“2016年6月”之间的数据 我有下面的模式(坦率地说)没有正确构建(并且它没有带回我想要的角色) 我不熟悉使用正则表达式,有人能帮我正确的表达吗 2016年5月ef 2016年6月efef 2016年5月2016年6月2016年5月 dffdg def efef 2016年6月 2016年5月 2016年6月 如果假设“2016年5月”和“2016年6月”交替出现,且前者先出现,则 x <- "May 2016 A Jun
x <- "May 2016 A Jun 2016 B May 2016 Jun 2016 May 2016 C Jun 2016 May 2016 Jun 2016"
sub("(.*?May 2016.*?Jun 2016){2}.*?May 2016(.*?)Jun 2016.*", "\\2", x)
[1] " C "
x给你(这需要perl=TRUE
):
说明:
(?s)
激活单线选项
(?:*2016年5月){3}
匹配2016年5月
3次,中间随机文本
\K
放弃迄今为止与匹配值不匹配的内容
*?
匹配任何内容
(?=2016年6月)
。。。截至2016年6月第一次出现
- 有两种方法
tt <- readLines(textConnection("May 2016 ef Jun 2016 efef May 2016 Jun 2016 May 2016
dffdg def efef
Jun 2016
May 2016
Jun 2016"))
(tt <- paste0(tt, collapse = ''))
# [1] "May 2016 ef Jun 2016 efef May 2016 Jun 2016 May 2016dffdg def efefJun 2016May 2016Jun 2016"
m <- gregexpr('May 2016(.*?)Jun 2016', tt, perl = TRUE)
mapply(function(x, y) substr(tt, x, x + y - 1),
attr(m[[1]], 'capture.start'), attr(m[[1]], 'capture.length'))[3]
# [1] "dffdg def efef"
gsub('May.*May.*May 2016(.*?)Jun 2016.*', '\\1', tt)
# [1] "dffdg def efef"
tt如果您认为您的正则表达式不正确,那么您必须给出要匹配内容的精确表示。也就是说,May_May_May_Jun_Jun_Jun_Jun_
或此类组合。因此我们可以假设我们有“……2016年5月……2016年6月……2016年5月……2016年6月……”等等?也就是说,它们交替出现,从五月开始?你的假设是对的。同时,为没有明确表示歉意。我打算从字符串中得到的是2016年5月2016年6月2016年5月2016年6月2016年5月2016年6月
在进行必要的修订后可能会有所帮助,以说明制作R-regex模式时需要额外的转义字符。非常感谢代码和演示中的解释。非常有用。但我仍然无法排除这几个月。我对您的模式进行了以下调整(?:*?2016年5月){3}\K(*)(?=2016年6月)
对不起,我想我自己回答了这个问题。我错过了<代码> >代码>中间的代码>((s))(?:*?2016年5月){ 3 } \(*?)(?= Jun 2016)< /代码>作品。great@Casimir哎呀,谢谢你纠正了我愚蠢的错误,我不知道我怎么会错过这个,因为解释是为了正确的模式:)
(?s)(?:.*?May 2016){3}\K.*?(?=Jun 2016)
tt <- readLines(textConnection("May 2016 ef Jun 2016 efef May 2016 Jun 2016 May 2016
dffdg def efef
Jun 2016
May 2016
Jun 2016"))
(tt <- paste0(tt, collapse = ''))
# [1] "May 2016 ef Jun 2016 efef May 2016 Jun 2016 May 2016dffdg def efefJun 2016May 2016Jun 2016"
m <- gregexpr('May 2016(.*?)Jun 2016', tt, perl = TRUE)
mapply(function(x, y) substr(tt, x, x + y - 1),
attr(m[[1]], 'capture.start'), attr(m[[1]], 'capture.length'))[3]
# [1] "dffdg def efef"
gsub('May.*May.*May 2016(.*?)Jun 2016.*', '\\1', tt)
# [1] "dffdg def efef"