【问题标题】:Regex find the string between last two quotes " "?正则表达式找到最后两个引号之间的字符串“”?
【发布时间】:2020-05-26 04:58:54
【问题描述】:

例如,这是我的字符串 -> abcd 1234abcda="author 1" content="author 2.">\n

我只想要字符串author 2.,通过在R中使用函数str_extract()。我怎样才能使用正则表达式来做到这一点?非常感谢。

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:

    你可以使用:

    string = 'abcd 1234abcda="author 1" content="author 2.">\n'
    sub('.*"(.*)".*', '\\1', string)
    #[1] "author 2."
    

    str_match

    library(stringr)
    str_match(string, '.*"(.*)"')[, 2]
    

    另一种选择是提取带有“作者”后跟数字的所有值,然后使用tail 选择最后一个值。

    tail(str_extract_all(string, 'author \\d+')[[1]], 1)
    

    【讨论】:

    • 你能解释一下为什么 sub('.*"(.*)".*', '\\1', string) 不会选择“作者1”吗?正则表达式对我来说看起来像任何“任何东西”,所以我不知道为什么不会选择“作者 1”。谢谢。
    • 这是因为正则表达式默认是贪婪的,这意味着它会在返回匹配之前尝试捕获尽可能多的字符。如果您想返回“作者 1”作为输出,您可以使正则表达式不贪婪,这可以通过使用 ? 来完成。所以sub('.*?"(.*?)".*', '\\1', string) 会给出“author 1”。
    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多