如何使用str_replace在不删除字母的情况下分隔字符串中的单词?

n9vozmp4  于 2023-06-03  发布在  其他
关注(0)|答案(3)|浏览(158)

我想把字符串中的单词分开,并在它们之间加一个空格。我怎么才能做到这一点,而不删除一些字母使用str_replace?

s1 <- c("Employee_Name", "EmpID", "MarriedID", "MaritalStatusID", "GenderID", 
        "EmpStatusID") |> print()
#> [1] "Employee_Name"   "EmpID"           "MarriedID"       "MaritalStatusID"
#> [5] "GenderID"        "EmpStatusID"
s1|> 
 stringr::str_remove_all("_") |> 
 # I want to separate the  words in  the string and add a space in between
 stringr::str_replace_all("([a-z][A-Z])", " ")
#> [1] "Employe ame"   "Em D"          "Marrie D"      "Marita tatu D"
#> [5] "Gende D"       "Em tatu D"

创建于2023-05-29带有reprex v2.0.2
我尝试了stringr::str_replace_all(“([a-z][A-Z])",““),但这会删除与模式匹配的字母。

cwtwac6a

cwtwac6a1#

使用OR操作符|gsub,这只是一行代码。

gsub('_|(?<=[a-z])(?=[A-Z])', ' ', s1, perl=TRUE)
# [1] "Employee Name"     "Emp ID"            "Married ID"        "Marital Status ID"
# [5] "Gender ID"         "Emp Status ID"
np8igboo

np8igboo2#

您希望使用lookbehind和lookahead:

library(stringr)

s1 |>
  str_remove_all("_") |>
  str_replace_all("(?<=[a-z])(?=[A-Z])", " ")
# [1] "Employee Name"     "Emp ID"            "Married ID"       
# [4] "Marital Status ID" "Gender ID"         "Emp Status ID"

或者,使用反向引用捕获组:

s1 |>
  str_remove_all("_") |>
  str_replace_all("([a-z])([A-Z])", "\\1 \\2")
# [1] "Employee Name"     "Emp ID"            "Married ID"       
# [4] "Marital Status ID" "Gender ID"         "Emp Status ID"
ztmd8pv5

ztmd8pv53#

s1 <- c("Employee_Name", "EmpID", "MarriedID", "MaritalStatusID", "GenderID", 
        "EmpStatusID")
str_replace_all(s1, '([A-Z]+)', ' \\1') |>
  str_replace_all('_', ' ') |>
  str_squish() |>
  print()
[1] "Employee Name"     "Emp ID"            "Married ID"        "Marital Status ID" "Gender ID"         "Emp Status ID"

相关问题