使用 gsub 根据特殊字符分割名称

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

我有以下名字,我正在尝试将其更改为名字、姓氏格式。

myNamesDup
"Cross K / Cross M"  "Davis L/Harper C"  "Williams M / 
Brown M G" "Greening E-L / Roberts J" "Jones Williams D/Browning A"

What I am trying to achieve;

"K Cross/M Cross"  "L Davis/C Harper"  "M Williams/M G 
 Brown " "E-L Greening/j Roberts" "A Jones Williams/A Browning"

我为此尝试了一些方法但不成功,主要是因为我认为是特殊字符。

The closest I got to this is by using;

gsub("([A-Za-z]*) (.*)/(.*) ([A-Za-z]*)", "\\2 \\1/\\4 \\3", myNamesDup)

这让我非常接近,似乎在双桶名称和 2 个首字母缩写上失败了

r regex string
1个回答
0
投票

您可以尝试使用

strsplit
sub
,如下所示

> unlist(lapply(strsplit(myNames, "/"), \(x) paste0(sub("(\\S+) (.*)", "\\2 \\1", trimws(x)), collapse = "/")))
[1] "K Cross/M Cross"             "L Davis/C Harper"
[3] "M Williams/M G Brown"        "E-L Greening/J Roberts"
[5] "Williams D Jones/A Browning"
© www.soinside.com 2019 - 2024. All rights reserved.