Pablo Boswell
Pablo Boswell

Reputation: 845

Regex to extract county name from string

Trying to create a regex in R to extract the county name from a string. Of course, you can't just grab the first word in front of the word "county" because some counties have a 2- or 3-word name. In this particular dataset, there are some other tricky expressions to work around. This is my first attempt:

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")]

Any help would be greatly appreciated!

Upvotes: 3

Views: 269

Answers (1)

lukeA
lukeA

Reputation: 54247

Another strategy: use a list of possible county names:

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"

Upvotes: 2

Related Questions