如何从地址字符串提取含数字的门牌号并拆分楼宇名称?
To split your address strings into door number and building name columns, we can use a targeted regular expression to capture the two components—even when door numbers include non-numeric characters like letters, prefix words, or hyphens. Here's how to do it in R:
Step-by-Step Explanation
The core idea is to write a regex pattern that matches all the varied door number formats present in your data, then extract those matches along with the remaining building name. The pattern accounts for:
- Simple numeric door numbers (e.g., "5")
- Alphanumeric numbers (e.g., "22A")
- Hyphenated ranges (e.g., "2-3")
- Prefixed numbers (e.g., "Flat 19", "Room 1", "No 17")
Code Implementation
First, let's define our input data and regex pattern:
# Input address vector 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") # Regex pattern to capture door number (group 1) and building name (group 2) pattern <- "^((?:Flat|Room|No)\\s+\\d+|\\d+(?:-\\d+)?|\\d+[A-Za-z])\\s+(.*)$"
Using stringr (Tidyverse)
If you're using the stringr package (part of the tidyverse), str_match makes extracting groups straightforward:
library(stringr) # Extract matches from each address matches <- str_match(add, pattern) # Convert matches to the desired data frame aim <- data.frame( No = matches[, 2], Building = matches[, 3], stringsAsFactors = FALSE ) # View the result print(aim)
Using Base R
If you prefer base R, use regexec and regmatches to achieve the same result:
# Extract matches using base R functions matches <- regmatches(add, regexec(pattern, add)) # Build the data frame by extracting groups from each match aim <- data.frame( No = sapply(matches, function(x) x[2]), Building = sapply(matches, function(x) x[3]), stringsAsFactors = FALSE ) # View the result print(aim)
Output
Both methods will produce exactly your expected result:
No Building 1 5 Ark Royal House 2 22A Blington Garden Lincoln Street 3 Flat 19 PICTON HOUSE 4 2-3 Royal Albert Court 5 Room 1 Grand Hall 6 No 17 The Dell Alpha House
Customization Tips
If you encounter other door number formats (like "Suite 45" or "12/34"), simply expand the regex pattern to include those cases. For example, to add support for "Suite" prefixes and slash-separated ranges:
pattern <- "^((?:Flat|Room|No|Suite)\\s+\\d+|\\d+(?:[-/]\\d+)?|\\d+[A-Za-z])\\s+(.*)$"
This updated pattern now handles additional formats like "Suite 45" and "12/34".
内容的提问来源于stack exchange,提问作者Phil Wu

