首页 > 解决方案 > 如何从字符串中提取数字,包括数字之前的所有文本

问题描述

我有一个地址列表,其中包含 (1) 门牌号和 (2) 建筑物名称。我希望将字符串分成两列。棘手的部分是一些门牌号码包含字符,例如“221B Baker Street”。

下面的例子:

add <- c("5 Ark Royal House" , 
     "22A Blington Garden Lincoln Street", 
     "Flat 19 PICTON HOUSE" , 
     "2-3 Royal Albert Court" , 
     "Room 1 Grand Hall", 
     "No 17 The Dell Alpha House")

理想的结果如下所示:

aim <- data.frame("No"=as.character(c("5", "22A", "Flat 19", "2-3", "Room 1", "No 17")), 
              "Building" = as.character(c("Ark Royal House", 
                                          "Blington Garden Lincoln Street" , 
                                          "PICTON HOUSE", 
                                          "Royal Albert Court" , 
                                          "Grand Hall" , 
                                          "The Dell Alpha House")))

标签: rregex

解决方案


使用stringr

library(stringr)
lst <- str_match_all(add, "^(\\D*\\d[-\\w]*)\\s+(.+)")

(aim <- setNames(as.data.frame(do.call(rbind, lst)),
                c("all", "No", "Building")))

或者在香草 R 中:

pattern <- "^(\\D*\\d[-\\w]*)\\s+(.+)"
lst <- regmatches(add, regexec(pattern, add, perl = T))
(aim <- setNames(as.data.frame(do.call(rbind, lst)),
                 c("all", "No", "Building")))


两者都会产生

                                 all      No                       Building
1                  5 Ark Royal House       5                Ark Royal House
2 22A Blington Garden Lincoln Street     22A Blington Garden Lincoln Street
3               Flat 19 PICTON HOUSE Flat 19                   PICTON HOUSE
4             2-3 Royal Albert Court     2-3             Royal Albert Court
5                  Room 1 Grand Hall  Room 1                     Grand Hall
6         No 17 The Dell Alpha House   No 17           The Dell Alpha House

请参阅regex101.com 上的表达式演示。


推荐阅读