r - 用标点符号提取字符串的一部分
问题描述
我有一个字符串:
string <- "newdatat.scat == \"RDS16\" ~ \"Asthma\","
我想单独提取:
RDS16
Asthma
到目前为止我尝试过的是:
extract <- str_extract(string,'~."(.+)')
但我只能得到:
~ \"Asthma\",
如果您有答案,您能否也解释一下它背后的正则表达式?我很难将字符串模式转换为正则表达式。
解决方案
如果您只需要提取由 包围的部分"
,则可以使用以下内容。模式".*?"
首先匹配"
,然后.*?
表示尽可能少的字符,最后匹配另一个"
。这将为您提供包括"
双引号的字符串;然后,您只需删除双引号即可进行清理。
请注意,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)
推荐阅读
- mysql - Mysql 拒绝连接到 Docker 上的管理员
- remote-access - rdp 正在断开连接
- javascript - Azure Text to Speech Throttled due to too many requests websocket error code: 1007 with only 3 concurrent requests
- google-cloud-platform - GCP - 我们可以强制用户在创建资源时添加标签吗?
- active-directory - 根据授权码获取自定义策略名称
- swift - 如何让 UIView 背景变成磨砂黑色?迅速?
- nuxt.js - PurgeCSS 忽略 whitelistPatterns 中的正则表达式并删除 TailwindCSS 类(在 NuxtJS 上)
- python - 如何使函数等于变量?
- sbt - 我收到这个 sbt 错误,有什么办法可以解决这个问题
- list - Dart:我如何计算一个特定整数列表的平均值,其中 X 个其他整数列表只有一个函数