最后一个 / 和第一个下划线之后的正则表达式匹配

Regex match after last / and first underscore

假设我有以下字符串:

string = "path/stack/over_flow/Pedro_account"

我有兴趣匹配最后一个 / 之后和第一个 _ 之前的前 2 个字符。所以在这种情况下,所需的输出是:

Pe

到目前为止我所拥有的是 substr 和 str_extract:

的混合
substr(str_extract(string, "[^/]*$"),1,2)

这当然会给出答案,但我相信也有一个很好的正则表达式,这就是我正在寻找的。

你可以使用

library(stringr)
str_extract(string, "(?<=/)[^/]{2}(?=[^/]*$)")
## => [1] "Pe"

参见R demo and the regex demo详情:

  • (?<=/) - 一个紧跟 / 字符
  • 的位置
  • [^/]{2} - /
  • 以外的两个字符
  • (?=[^/]*$) - 紧接在 / 以外的零个或多个字符之前的位置,直到字符串结尾。

使用basename获取最后一个文件夹名,然后substring:

substr(basename("path/stack/over_flow/Pedro_account"), 1, 2)
# [1] "Pe"

删除所有内容直到最后 / 并提取前 2 个字符。

基础 R -

string = "path/stack/over_flow/Pedro_account"
substr(sub('.*/', '', string), 1, 2)
#[1] "Pe"

stringr

substr(stringr::str_remove(string, '.*/'), 1, 2)

您可以将 str_match 与捕获组一起使用:

  • /字面匹配
  • ([^/_]{2})组 1
  • 中捕获除 /_ 以外的 2 个字符
  • [^/]* 匹配 /
  • 以外的可选字符
  • $ 字符串结束

看到一个regex demo and a R demo.

例子

library(stringr)
string = "path/stack/over_flow/Pedro_account"
str_match(string, "/([^/_]{2})[^/]*$")[,2]

输出

[1] "Pe"