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

R语言中如何提取两个字符串的左侧连续匹配词并终止?

提取两个字符串左侧连续匹配词的R实现

给定两个字符串,我们需要从左到右逐词对比,保留开头连续匹配的部分,遇到不匹配词就停止,最终拼接成新字符串。以下是具体实现方案:

基于Base R的代码(无需额外包)

x <- "Here is a test of words and stuff."
y <- "Here is a better test of words and stuff."

# 按空格拆分字符串为单词向量
x_words <- strsplit(x, "\\s+")[[1]]
y_words <- strsplit(y, "\\s+")[[1]]

# 定位第一个不匹配的单词位置
first_mismatch <- which(x_words != y_words)[1]

# 生成结果字符串
result <- if (is.na(first_mismatch)) {
  # 所有单词都匹配时取全部内容
  paste(x_words, collapse = " ")
} else {
  # 截取到第一个不匹配词之前的部分
  paste(x_words[1:(first_mismatch - 1)], collapse = " ")
}

# 输出结果
cat('"', result, '"', sep = "")

运行后输出:

"Here is a"

代码说明

  • strsplit(x, "\\s+"):通过正则表达式匹配任意数量的空格,将字符串拆分为单词列表,[[1]]用于提取列表中的向量元素。
  • which(x_words != y_words)[1]:找到第一个词不相等的索引位置,如果所有词都匹配,该结果会返回NA。
  • paste(..., collapse = " "):将匹配的单词向量重新拼接为完整字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:45:32