关于问题域有许多未解决的问题。除此之外,让我们使用以下数据,其中包含问题中提供的样本数据用于正匹配,以及一些附加样本数据用于负匹配(我使用的是R version 2.14.1 (2011-12-22)):
x <- c("140,000 mostly freeway miles", "173k commuter miles. ", "154K(all highway) miles", "1,24 almost but not mostly freeway miles", "1,2,3,4K MILES")
1,2,3,4K MILES 被添加为否定匹配,因为问题将 near 定义为 1-3 words apart,并且它的“邻近词”为零。
如果我们使用以下...
sub('[\\d,]+k?\\s+(([^\\s]+\\s+){1,3})miles', '\\1', x, ignore.case = TRUE, perl = TRUE)
...我们得到:
[1] "mostly freeway "
[2] "commuter . "
[3] "154K(all highway) miles"
[4] "1,24 almost but not mostly freeway miles"
[5] "1,2,3,4K MILES"
可能不是你想要的结果。由于数据未标准化,因此您必须使用会变得非常复杂的正则表达式模式。正如Justin 在他的answer、clean up the data first then do some simpler matching 中所建议的那样。
您可以将数据标准化如下:
y <- gsub('\\pP+', ' ', x, perl = TRUE)
y <- gsub('\\s+', ' ', y, perl = TRUE)
y <- gsub('^\\s+|\\s+$', '', y, perl = TRUE)
y <- gsub('(\\d)\\s(?=\\d)', '\\1\\2', y, perl = TRUE)
有关详细信息,请参阅下面的参考资料。这基本上是删除标点符号并确保单词由一个空格分隔。这将为您留下y of:
[1] "140000 mostly freeway miles"
[2] "173k commuter miles"
[3] "154K all highway miles"
[4] "124 almost but not mostly freeway miles"
[5] "1234K MILES"
现在删除与您要查找的内容不匹配的行:
y <- sub('^(?!\\d+k?\\s((?!miles)[^\\s]+\\s){1,3}miles).*$', '', y, ignore.case = TRUE, perl = TRUE)
y
[1] "140000 mostly freeway miles" "173k commuter miles"
[3] "154K all highway miles" ""
[5] ""
最后,得到“近词”:
y <- sub('^\\d+k?\\s((?!miles)[^\\s]+(\\s(?!miles)[^\\s]+){0,2})\\smiles', '\\1', y, ignore.case = TRUE, perl = TRUE)
y
[1] "mostly freeway" "commuter" "all highway" ""
[5] ""
可能有更简单的方法来规范化数据,但这为您提供了一些正则表达式示例。
有关详细信息,请参阅: