正则表达式 - 通过 gsub 中的正则表达式匹配排除 URL 的特定部分

regex - excluding a specific part of an URL via regex match in gsub

我正在使用以下矢量:

vec <- c("http://statistics.gov.scot/id/statistical-geography/S02000002",
         "http://statistics.gov.scot/id/statistical-geography/S02000003")

我想从向量中删除 http://statistics.gov.scot/id/statistical-geography/。我目前的 regex 语法:

vec_cln <- gsub(replacement = "", x = vec, perl = TRUE, fixed = FALSE,
                   pattern = "([[:alnum:]]|[[:punct:]]|)(?<!S\d{8})")

但这只留下向量 vec 的最后一位数字。我猜问题出在 \d{8},但是,我不清楚如何解决它。我在 regex101 上尝试了各种解决方案,但无济于事。一些例子:

我要实现的目标可以简单地概括为:*匹配所有内容,直到找到大写字母 S8 位数字之后。

备注

我想通过 gsubregex 得出解决方案我不想使用:

您可以使用

获得结果
sub(".*(S\d{8})", "\1", vec)

demo

使用 .*,我们匹配任意数量的(* - 0 个或更多)任何字符,但换行符最多为 S,后跟 8 位数字(S\d{8}).由于 (S\d{8}) 位于未转义的括号内,因此与此子模式匹配的子字符串被放入捕获组 #1 中。使用 \1 反向引用,我们在结果中恢复捕获的文本。

在常规 expressions.info.

查看更多关于 backreferences and capturing groups 的信息

注意:如果您在 S+8 digits 之后有更多文字,您可以使用

sub("^.*(S\d{8}).*$", "\1", vec)

这里是稍微漂亮一点的语法:

library(rex)
library(stringi)
library(magrittr)

regex_1 = rex("S", digits)

vec <- c("http://statistics.gov.scot/id/statistical-geography/S02000002",
         "http://statistics.gov.scot/id/statistical-geography/S02000003")

vec %>% stri_extract_last_regex(regex_1)