使用字符串模式匹配为 R 中的变量赋值
Assigning value to variable in R with string pattern matching
我必须检测 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] 虽然
没有解决它
str_match
returns 一个矩阵,第一列是完全匹配,而第二列是捕获组。因为这里我们需要捕获组,所以我们可以提取第二列。
xx <- stringr::str_match(x, "Name: (.*) ")[, 2]
xx
#[1] "Sunil Raperia"
然而,这也可以使用 sub
在 base R 中完成
sub('Name: ', '', x)
或
sub('Name: (.*) ', '\1', x)
我必须检测 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] 虽然
没有解决它str_match
returns 一个矩阵,第一列是完全匹配,而第二列是捕获组。因为这里我们需要捕获组,所以我们可以提取第二列。
xx <- stringr::str_match(x, "Name: (.*) ")[, 2]
xx
#[1] "Sunil Raperia"
然而,这也可以使用 sub
sub('Name: ', '', x)
或
sub('Name: (.*) ', '\1', x)