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

R语言如何使用stringr移除字符串后缀并保留含_other的字符串

你现有写法的问题出在正则规则设计错误:[^other]属于单字符匹配规则,只会匹配单个不属于o、t、h、e、r这五个字母的字符,无法实现「排除整个_other后缀」的需求。

正确方案可以使用负向前瞻正则_(?!other).*,搭配str_remove即可实现预期效果,具体代码如下:

library(stringr)

# 测试文本
testregex <- c("d1_1", "d2_other", "d1_1_2", "test", "d5_extra", "a22_10")

# 正确代码
result <- str_remove(testregex, "_(?!other).*")

# 验证结果和预期一致
expected <- c("d1", "d2_other", "d1", "test", "d5", "a22")
identical(result, expected) # 输出为 TRUE

正则规则说明

  • _ 匹配作为后缀开头的下划线
  • (?!other) 是负向前瞻断言,要求当前下划线后不能紧跟着完整的other字符串
  • .* 匹配符合条件的下划线之后的所有剩余内容
  • 满足规则的后缀会被一次性移除,不需要使用str_remove_all

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:24:04