【问题标题】:Extract text in two columns from a string从字符串中提取两列中的文本
【发布时间】:2021-03-07 20:43:57
【问题描述】:

我有一张表,其中一列的数据如下:

table$test_string<- "[projectname](https://somewebsite.com/projectname/Abc/xyz-09)"

1.) 我试图在一个列的方括号内提取该字符串的第一部分,即

table$project_name &lt;- "projectname"

使用正则表达式:

project_name <- "^\\[|(?:[a-zA-Z]|[0-9])+|\\]$"
table$project_name <- str_extract(table$test_string, project_name)

如果我在表的 1 个值(单独 1 行)上测试正则表达式,则上面的正则表达式可以使用 str_extract_all(table$test_string, project_name[[1]][2]).

但是,当我将正则表达式模式应用于整个表时,我得到 NA,如果我使用 str_extract_all,则会出错。

2.) 字符串的第二部分,即另一列中的 URL,

table$url_link &lt;- "https://somewebsite.com/projectname/Abc/xyz-09"

我正在为 URL 使用以下正则表达式:

url_pattern &lt;- "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"

table$url_link &lt;- str_extract(table$test_string, url_pattern)

这适用于整个表格,但是,我仍然在 url 链接中得到最后一个括号。

我在这里缺少什么?为什么第一个正则表达式单独工作而不是整个表? 而对于 url,我怎样才能得到最后一个括号?

【问题讨论】:

    标签: r regex pattern-matching stringr


    【解决方案1】:

    感觉你可以通过使用括号来分组捕获来大大简化事情。例如:

    test_string<- "[projectname](https://somewebsite.com/projectname/Abc/xyz-09)"
    
    regex <- "\\[(.*)\\]\\((.*)\\)"
    
    gsub(regex, "\\1", test_string)
    #> [1] "projectname"
    
    gsub(regex, "\\2", test_string)
    #> [1] "https://somewebsite.com/projectname/Abc/xyz-09"
    

    【讨论】:

    • 哇,这比我的方法容易多了!像魅力一样工作!非常感谢!
    • 很高兴为您提供帮助!随意接受您最终使用的答案(至少还有另一个好的答案,您可能想尝试一下)。
    【解决方案2】:

    我们可以使用qdapRegex的便捷功能

    library(qdapRegex)
    rm_round(test_string, extract = TRUE)[[1]]
    #[1] "https://somewebsite.com/projectname/Abc/xyz-09"
    
    rm_square(test_string, extract = TRUE)[[1]]
    #[1] "projectname"
    

    数据

    test_string<- "[projectname](https://somewebsite.com/projectname/Abc/xyz-09)"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      相关资源
      最近更新 更多