我想从以下字符串中提取状态缩写(2个字母)和邮政编码(4或5个数字)
address <- "19800 Eagle River Road, Eagle River AK 99577
907-481-1670
230 Colonial Promenade Pkwy, Alabaster AL 35007
205-620-0360
360 Connecticut Avenue, Norwalk CT 06854
860-409-0404
2080 S Lincoln, Jerome ID 83338
208-324-4333
20175 Civic Center Dr, Augusta ME 4330
207-623-8223
830 Harvest Ln, Williston VT 5495
802-878-5233
"
对于邮政编码,我尝试了一些在这里找到的方法,但是由于5号街道地址或仅包含4个数字的邮政编码而无法使用
text <- readLines(textConnection(address))
library(stringi)
zip <- stri_extract_last_regex(text, "\\d{5}")
zip
library(qdapRegex)
rm_zip3 <- rm_(pattern="(?<!\\d)\\d{5}(?!\\d)", extract = TRUE)
zip <- rm_zip3(text)
zip
[1] "99577" "1670" "35007" "0360" "06854" "0404" "83338" "4333" "4330" "8223" "5495" "5233" NA
对于国家缩写,我不知道如何提取
任何帮助表示赞赏!提前致谢!
编辑1:包括电话号码
最佳答案
提取邮政编码的代码:
zip <- str_extract(text, "\\d{5}")
提取状态码的代码:
states <- str_extract(text, "\\b[A-Z]{2}(?=\\s+\\d{5}$)")
提取电话号码的代码:
phone <- str_extract(text, "\\b\\d{3}-\\d{3}-\\d{4}\\b")
注意:您的数据似乎有问题,因为最后2个邮政编码应为5个字符长而不是4个字符。
4330
实际上应为04330
。如果您无法控制数据源,但可以确定它们是美国代码,则可以根据需要在左侧填充0。但是,由于您正在寻找4或5个字符的解决方案,因此可以使用以下方法:提取邮政编码的代码(在前面查找空格,在后面查找换行符,以便不选择电话号码或地址的一部分)
zip <- str_extract(text, "(?<= )\\d{4,5}(?=\\n|$)")
提取状态码的代码:
states <- str_extract(text, "\\b[A-Z]{2}(?=\\s+\\d{4,5}$)")
演示:https://regex101.com/r/7Im0Mu/2
关于r - 从字符串中提取状态缩写和邮政编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43789289/