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

在R(dplyr)中使用grepl筛选邻近双词汇的正则错误问题

解决R中grepl正则匹配邻近词汇的报错问题

问题原因

报错Error: '\W' is an unrecognized escape in character string是因为R字符串中的反斜杠需要双重转义,单个\会被R解析为转义符,而正则需要的\b(单词边界)、\W(非单词字符)必须写成\\b、\\W。另外原正则表达式存在括号不匹配的问题,导致语法错误。

修正方案

要匹配tumo(u)r与目标词汇(如colon或cancer)相隔不超过3个词的情况,需完成以下调整:

  • 修复转义字符,用\\替代单个\
  • 修正正则的括号配对,合理分组
  • 覆盖双向匹配场景(两个词的顺序可能互换)

示例代码

library(tibble)
library(dplyr)

example.df <- tibble(
  number = 1:6,
  AB = c(
    'tumor of the colon is a very hard disease to cure',
    'breast cancer is also known as a neoplasia of the breast',
    'tumour of the colon is bad',
    'colon cancer is also bad',
    'colon and tumor are close',
    'cancer with tumour within three words'
  )
)

# 匹配tumo(u)r与colon相隔不超过3个词(双向)
filtered_colon <- example.df %>% 
  filter(grepl(
    "\\b(tumor|tumour)\\W+(?:\\w+\\W+){0,3}colon\\b|\\bcolon\\W+(?:\\w+\\W+){0,3}(tumor|tumour)\\b",
    AB, 
    ignore.case = TRUE
  ))

# 匹配tumo(u)r与cancer相隔不超过3个词(双向)
filtered_cancer <- example.df %>% 
  filter(grepl(
    "\\b(tumor|tumour)\\W+(?:\\w+\\W+){0,3}cancer\\b|\\bcancer\\W+(?:\\w+\\W+){0,3}(tumor|tumour)\\b",
    AB, 
    ignore.case = TRUE
  ))

# 查看结果
print(filtered_colon)
print(filtered_cancer)

正则逻辑说明

  • \\b:匹配单词边界,确保仅匹配完整单词
  • (tumor|tumour):匹配tumor或tumour两种拼写
  • \\W+:匹配一个或多个非单词字符(如空格、标点)
  • (?:\\w+\\W+){0,3}:非捕获组,匹配0到3个“单词+非单词字符”组合,即最多间隔3个词
  • |:分隔两种顺序的匹配规则(目标词在前/在后)

运行结果

  • filtered_colon会筛选出第1、3、5行(包含tumo(u)r和colon且间隔≤3词)
  • filtered_cancer会筛选出第6行(包含tumour和cancer且间隔≤3词)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:25:18