I'm using R for string processing. I have a data frame with a column of strings, say:
df <- data.frame(textcol=c("In this substring would like to find the position of this substring",
"I would also like to find the position of thes substring",
"No match here","No mention of this substrangy thing"))
matchPattern <- "this substring"
I am searching for a function that (depending on a distance parameter of some sort, say Jarro-Winkler) would take my matchPattern, compare it to every row of the data frame text column, and return the exact position of the match within the matched string, i.e. 36 (unless I miscounted) for the first element, and (perhaps) 43 for the second, NA for the third and 14 (?) for the the fourth.
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"
来源:https://stackoverflow.com/questions/31843171/position-of-approximate-substring-matches-in-r