使用 gsub 匹配带有字符、数字和空格的子字符串

Match a substring with character, digits and spaces with gsub

我有一个像这样的字符串:

a <- '{:name=>"krill", :priority=>2, :count=>1}, {:name=>"vit a", :priority=>2]}, {:name=>"vit-b", :priority=>2, :count=>1}, {:name=>"vit q10", :priority=>2]}'

我想通过 str_match 解析 ':name=>" ' 和 ' " '

中的元素
krill
vit a
vit-b
vit q10

到目前为止我试过:

str_match(a, ':name=>\"([A-Za-z]{3})')

但是没用。

感谢任何帮助

您可以使用

提取这些值
> regmatches(a, gregexpr(':name=>"\K[^"]+', a, perl=TRUE))
[[1]]
[1] "krill"   "vit a"   "vit-b"   "vit q10"

:name=>"\K[^"]+ pattern 匹配

  • :name=>" - 文字子串
  • \K - 省略匹配中的子字符串
  • [^"]+ - ".
  • 以外的一个或多个字符

如果需要使用stringr包,使用str_extract_all:

> library(stringr)
> str_extract_all(a, '(?<=:name=>")[^"]+')
[[1]]
[1] "krill"   "vit a"   "vit-b"   "vit q10"

(?<=:name=>")[^"]+ 中,(?<=:name=>") 匹配紧跟在 :name=>" 之前的任何位置。

使用stringr正向回顾

library(stringr)
str_match_all(a, '(?<=:name=>")[^"]+')

[[1]]
     [,1]     
[1,] "krill"  
[2,] "vit a"  
[3,] "vit-b"  
[4,] "vit q10"