You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中提取特定模式后的子字符串

移除R字符串列表中开头的特定前缀

你可以用以下两种常见方法实现需求:

方法一:基础R的sub()函数

利用正则表达式匹配开头的数字+固定前缀模式,将其替换为空字符串:

mylist <- c("0-X-global-X-all_chondroitine-and-heparan-sulfate_synthesis", "100-X-global-X-all_retinol_metabolism", "2-X-global-X-all_type-I-ifn-response", "312-X-global-X-thrombolysis-factor_production")

result <- sub("^\\d+-X-global-X-", "", mylist)
print(result)

执行后输出:

[1] "all_chondroitine-and-heparan-sulfate_synthesis" "all_retinol_metabolism"                        
[3] "all_type-I-ifn-response"                       "thrombolysis-factor_production"

方法二:使用stringr包(tidyverse生态)

如果习惯tidyverse风格,用str_remove()更直观:

library(stringr)

mylist <- c("0-X-global-X-all_chondroitine-and-heparan-sulfate_synthesis", "100-X-global-X-all_retinol_metabolism", "2-X-global-X-all_type-I-ifn-response", "312-X-global-X-thrombolysis-factor_production")

result <- str_remove(mylist, "^\\d+-X-global-X-")
print(result)

正则表达式说明

^\\d+-X-global-X-的含义:

  • ^:匹配字符串的起始位置
  • \\d+:匹配1个或多个数字(对应开头的0、100、2、312这类内容)
  • -X-global-X-:匹配固定的前缀部分

内容的提问来源于stack exchange,提问作者Yulia Kentieva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 03:45:57