【问题标题】:Using regex and stringr to extract the last portion of a URL使用 regex 和 stringr 提取 URL 的最后一部分
【发布时间】:2020-04-27 12:33:37
【问题描述】:

我正在做数百个 URL 重定向,需要提取最后一个正斜杠之后的所有文本,所以:

/blog/2018/9/28/my_article1 变为 /my_article1

理想情况下,我想使用来自tidyversestringr 包。我在这里看到了一个类似的问题(不适用于 R):

Regex start searching from the end of the string (reverse)

...并尝试了这个:

df %>% 
  mutate(new.page = str_extract(old.page, "/[^\/]+$/"))

... 但得到错误: Error: '\/' is an unrecognized escape in character string starting ""/[^\/"

我尝试删除转义的反斜杠,但无济于事。

下面是原始 URL 的 dput 表示数据示例,其中 old.page 是我开始的地方,new.page 是我想要到达的地方。

structure(list(old.page = c("/blog/2018/9/28/my_article1", "/blog/2013/05/22/1735", 
                            "/blog/2013/02/27/my-goals", "/blog/2013/01/23/leading-change", 
                            "/blog/2013/11/19/2-blog-posts-in-1"), new.page = c("/my_article1", 
                                                                                "/1735", "/my-goals", "/leading-change", "/2-blog-posts-in-1"
                            )), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, 
                                                                                                       -5L))

【问题讨论】:

  • basename() 可能是一个简单的解决方案?

标签: r regex tidyverse stringr


【解决方案1】:

如果您想避免使用正则表达式,您可以使用basename()paste0() 是在新列中包含反斜杠。

df %>% 
  mutate(new.page = paste0("/", basename(old.page)))

或使用正则表达式

df %>%
  mutate(new.page = gsub('.*\\/', "/", old.page))

【讨论】:

  • 不知道有像basename 这样优雅的函数。也感谢您发布正则表达式。
【解决方案2】:

我们可以使用str_remove

library(dplyr)
library(stringr)
df %>% 
     mutate(new.page = str_remove(old.page, ".*(?=/)"))
# A tibble: 5 x 2
#  old.page                           new.page          
#  <chr>                              <chr>             
#1 /blog/2018/9/28/my_article1        /my_article1      
#2 /blog/2013/05/22/1735              /1735             
#3 /blog/2013/02/27/my-goals          /my-goals         
#4 /blog/2013/01/23/leading-change    /leading-change   
#5 /blog/2013/11/19/2-blog-posts-in-1 /2-blog-posts-in-1

使用str_extract,我们提取/,后跟不是/ 的字符,直到字符串的结尾($

df %>% 
     mutate(new.page = str_extract(old.page, "/[^/]+$"))

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 2018-07-31
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    相关资源
    最近更新 更多