Position of Approximate Substring Matches in R

佐手、 提交于 2019-12-06 04:28:00

You could use aregexec

## Get positions (-1 instead of NA)
positions <- aregexec(matchPattern, df$textcol, max.distance = 0.1)
unlist(positions)
# [1] 38 43 -1 15

## Extract matches
regmatches(df$textcol, positions)
# [[1]]
# [1] "this substring"
# 
# [[2]]
# [1] "thes substring"
# 
# [[3]]
# character(0)
# 
# [[4]]
# [1] "this substrang"

Edit

## A possibilty for replacing matches, or maybe `regmatches<-`
res <- regmatches(df$textcol, positions)
res[lengths(res)==0] <- "XXXX"  # deal with 0 length matches somehow
df$out <- Vectorize(gsub)(unlist(res), "Censored", df$textcol)
df$out
# [1] "I would like to find the position of Censored"     
# [2] "I would also like to find the position of Censored"
# [3] "No match here"                                     
# [4] "No mention of Censoredy thing"                     
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!