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

时间:2017-04-29 16:50:39

标签: r regex data.table

尝试在R中创建一个正则表达式,从字符串中提取县名。当然,你不能只抓住#34; county"这个词前的第一个单词。因为有些县有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")]

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

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

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"