r - 如何从字符串中提取数字,包括数字之前的所有文本
问题描述
我有一个地址列表,其中包含 (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")))
解决方案
使用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 上的表达式演示。
推荐阅读
- javascript - ESLint 未定义/被赋值但未使用
- yii - 如何隐藏 Yii 下拉列表搜索字段?
- python-3.x - 按字母顺序排列公司名称
- mysql - 如何将订单表添加到我的 SQL 数据库?
- sql - 如何在 SQL Server 中创建一个函数以将 2 个 datetime2 值与 GETDate 进行比较并返回一个布尔值
- c - 将客户端连接到具有相同 IP 和端口的两台服务器
- python - NameError:名称“变量”未定义 Python
- maven - Git-Flow Maven 插件:修补程序分支
- networking - IPFS 在 NAS 上运行,无法从联网机器连接到 API/网关
- arrays - 使用函数标记字符串输入