如何将 6 个数字的字符串中的一个或多个空格或空格替换为零?

问题描述 投票:0回答:1

我有以下数据框

dput(head(phone_numbers_df)) 

structure(list(phone_number = c("30 969166", "31    8941", "32   34057",  "33   24021", "34 685284", "36 226317"), prefix = c("30", "31",  "32", "33", "34", "36")), row.names = c(NA, -6L), class = c("tbl_df",  "tbl", "data.frame"))

phone_number 的后缀应该始终有 6 个数字。有些有 5 或 4 个,因为是从随机数生成的。如何用零替换空格?

我尝试了以下方法,但使用的正则表达式似乎无法正确检测空格

 library(tidyverse)

fixed_numbers <- phone_numbers_df %>%
  mutate(needs_replacement = str_detect(needs_replacement , "\\s{1,6}$")) %>%
  mutate_at(vars(needs_replacement), ~ ifelse(. == TRUE, str_replace(., "\\s{1,6}$", "000000"), .))

# Display the fixed phone numbers
print(fixed_numbers)

预先感谢您的帮助!

r regex replace whitespace detection
1个回答
0
投票

您不需要先检测然后更换。只需使用

str_replace_all()
就像

phone_numbers_df %>%
  mutate(needs_replacement = str_replace_all(phone_number,' ', '0')) 

# A tibble: 6 x 3
  phone_number prefix needs_replacement
  <chr>        <chr>  <chr>            
1 30 969166    30     300969166        
2 31    8941   31     3100008941       
3 32   34057   32     3200034057       
4 33   24021   33     3300024021       
5 34 685284    34     340685284        
6 36 226317    36     360226317   
© www.soinside.com 2019 - 2024. All rights reserved.