首页 > 解决方案 > 用标点符号提取字符串的一部分

问题描述

我有一个字符串:

string <- "newdatat.scat == \"RDS16\" ~ \"Asthma\","

我想单独提取:

RDS16
Asthma

到目前为止我尝试过的是:

extract <- str_extract(string,'~."(.+)')

但我只能得到:

~ \"Asthma\",

如果您有答案,您能否也解释一下它背后的正则表达式?我很难将字符串模式转换为正则表达式。

标签: r

解决方案


如果您只需要提取由 包围的部分",则可以使用以下内容。模式".*?"首先匹配",然后.*?表示尽可能少的字符,最后匹配另一个"。这将为您提供包括"双引号的字符串;然后,您只需删除双引号即可进行清理。

请注意,str_extract_all它用于返回所有匹配项,并且它返回一个字符向量列表,因此我们需要在删除双引号之前对列表进行索引。

library(stringr)
string <- "newdatat.scat == \"RDS16\" ~ \"Asthma\","

str_extract_all(string, '".*?"') %>%
  `[[`(1) %>%
  str_remove_all('"')
#> [1] "RDS16"  "Asthma"

reprex 包于 2021-06-21 创建(v1.0.0)


推荐阅读