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

在R语言中如何移除未紧跟数字的字符串内容?

移除未紧跟数字的字符串内容解决方案

针对你提供的R语言字符串处理场景,可以通过正则表达式结合stringr包实现需求,具体步骤如下:

核心代码实现

library(stringr)

# 原始数据
String <- c("NA; ab 1917; ajr 69; sb 700; sb 703; scarl m; ab 1672 a",
            "ab 18 sb 5 ab 1433 hdge; ab 1129 ab 184 ab 473 a",
            "ab 3 16 31 41 1134 1206 abuht",
            "ab 479 862 984 1626 asc")

df <- data.frame(String)

# 移除目标字符串并清理格式
df$Output <- str_replace_all(df$String, 
                             pattern = "\\b(?!NA\\b)(?<!\\d)\\D+\\b|\\b\\D+(?!\\d)\\b", 
                             replacement = "")
df$Output <- str_squish(str_replace_all(df$Output, ";\\s*;", ";;"))

代码说明

  1. 正则表达式匹配规则:
    • \\b(?!NA\\b)(?<!\\d)\\D+\\b:匹配除NA之外、前面无数字的纯非数字单词(如scarl、hdge、abuht)
    • \\b\\D+(?!\\d)\\b:匹配后面无数字的纯非数字单词(如ab 1672 a中的a)
  2. 格式清理:
    • str_squish:移除多余的连续空格
    • str_replace_all(df$Output, ";\\s*;", ";;"):保留移除单词后出现的连续分号(与示例输出格式一致)

运行结果

处理后df的Output列内容如下:

[1] "NA; ab 1917; ajr 69; sb 700; sb 703;; ab 1672"
[2] "ab 18 sb 5 ab 1433 ab 1129 ab 184 ab 473"     
[3] "ab 3 16 31 41 1134 1206"                      
[4] "ab 479 862 984 1626"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:40:42