【问题标题】:Assigning value to variable in R with string pattern matching使用字符串模式匹配为R中的变量赋值
【发布时间】:2020-02-06 02:16:06
【问题描述】:

我必须检测 Name: 并将值分配给任何变量。我正在尝试使用 str_match,但它只需要 Sunil

x = c("Name: Sunil Raperia ")
xx = str_match(x, "Name: (.*?) ")
xx

y = c("名称: 苏尼尔·拉佩里亚")

stringr::str_match(y, "Name: (.) ")[, 2] 当值在下一行时无法捕获该值。 stringr::str_match(y, "Name: (.) " /n)[, 2] 虽然没有解决它

【问题讨论】:

    标签: r string string-matching


    【解决方案1】:

    str_match 返回一个矩阵,第一列是完全匹配,而第二列是捕获组。因为这里我们需要捕获组,所以我们可以提取第二列。

    xx <- stringr::str_match(x, "Name: (.*) ")[, 2]
    xx
    #[1] "Sunil Raperia"
    

    但是,这也可以在基础 R 中使用 sub 完成

    sub('Name: ', '', x)
    

    sub('Name: (.*) ', '\\1', x)
    

    【讨论】:

    • 谢谢Ronak,我能解决,只是出于好奇,[,2]这个有什么用?
    • @SunilRaperia as str_match 返回一个包含 2 列的矩阵,我们使用 [, 2] 提取第二列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多