正则表达式从字符串中提取县名

标签 r regex data.table

尝试在 R 中创建正则表达式以从字符串中提取县名。当然,你不能只捕获“县”这个词前面的第一个词,因为有些县有一个 2 个或 3 个字的名称。在这个特定的数据集中,还有一些其他棘手的表达式需要解决。这是我的第一次尝试:

library(data.table)

foo <- data.table(foo=c("Unemployment Rate in Southampton County, VA"
                        ,"Personal Income in Southampton County + Franklin City, VA"
                        ,"Mean Commuting Time for Workers in Southampton County, VA"
                        ,"Estimate of People Age 0-17 in Poverty for Southampton County, VA"))

foo[,county:=trimws(regmatches(foo,gregexpr("(?<=\\bfor|in\\b).*?(?=(City|Municipality|County|Borough|Census Area|Parish),)",foo,perl=T)),"both")]

如有任何帮助,我们将不胜感激!

最佳答案

另一种策略:使用可能的县名列表:

library(maps)
library(stringi)
counties <- sapply(strsplit(map("county", plot=F)$names,",",T), "[", 2)
counties <- unique(sub("(.*?):.*", "\\1", counties))
counties <- sub("^st", "st.?", counties)
foo=c("Unemployment Rate in Southampton County, VA"
                        ,"Personal Income in Southampton County + Franklin City, VA"
                        ,"Mean Commuting Time for Workers in Southampton County, VA"
                        ,"Estimate of People Age 0-17 in Poverty for Southampton County, VA")
stri_extract_all_regex(
  foo, paste0("\\b(", paste(counties, collapse = "|"), ")\\b(?!\\s*city)"), case_insensitive=TRUE
)
# [[1]]
# [1] "Southampton"
# 
# [[2]]
# [1] "Southampton"
# 
# [[3]]
# [1] "Southampton"
# 
# [[4]]
# [1] "Southampton"

关于正则表达式从字符串中提取县名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43698187/

相关文章:

r - 在 R 中的对数标度图上绘制置信带

r - 如何安装多个包?

regex - R 正则表达式仅选择性地替换特定字符串位置的字符

r - 将第 r 行的值插入第 (r+1) 行,并将 1 插入到 data.table 中多列的第一行

r - data.table 列上的差异

R 的 Format 函数返回奇数结果

r - 向量化 Gsub 的问题

java - 替换属性文件键中的所有空格

javascript - RegExp.test() 根据调用方式(在哪里?)为相同的 str 返回不同的结果

r - 获取一段时间内的累积值计数