My raw data has a lot of personal information, so I am masking them in R. The sample data and my original code are below:
install.packages("stringr")
library(string)
x = c("010-1234-5678",
"John 010-8888-8888",
"Phone: 010-1111-2222",
"Peter 018.1111.3333",
"Year(2007,2019,2020)",
"Alice 01077776666")
df = data.frame(
phoneNumber = x
)
pattern1 = "\\d{3}-\\d{4}-\\d{4}"
pattern2 = "\\d{3}.\\d{4}.\\d{4}"
pattern3 = "\\d{11}"
delPhoneList1 <- str_match_all(df, pattern1) %>% unlist
delPhoneList2 <- str_match_all(df, pattern2) %>% unlist
delPhoneList3 <- str_match_all(df, pattern3) %>% unlist
I found three types of patterns from the dataset and each result is below:
> delPhoneList1
[1] "010-1234-5678" "010-8888-8888" "010-1111-2222"
> delPhoneList2
[1] "010-1234-5678" "010-8888-8888" "010-1111-2222" "018.1111.3333" "007,2019,2020"
> delPhoneList3
[1] "01077776666"
Pattern1 is the typical type of phone number in my country using a dash, but someone types in the number like pattern2 using a comma. However, pattern2 also includes pattern1, so it detects the other pattern like a series of the year. It is an unexpected result.
My question is how to match the exact pattern that I define. The pattern2 includes excessive patterns such as "007,2019,2020"
from "Year(2007,2019,2020)"
.
Additionally, the next step is masking the number using the below code:
for (phone in delPhoneList1) {
df$phoneNumber <- gsub(phone, "010-9999-9999", df$phoneNumber)
}
I think the code is perfect for me, but if you had a more efficient way, please let me know.
Thanks.