我是(新手)使用 R 和正则表达式来编写用于操作data.frame列中字符串的正则表达式。我的数据在 R 中是这样的:
c1
Peter Parker
Hawk & Dove
J Jonah Jameson
3JPX spo
Bruce Wayne
Run Code Online (Sandbox Code Playgroud)
我想要得到的是第二列“c2”,它由以下字符串组成:
c2
PeterP
Hawk&D
JJJ
3JPXs
BruceW
Run Code Online (Sandbox Code Playgroud)
基本上我想要字符串的整个第一个单词(无论长度如何)以及后面每个单词的第一个字母数字元素。我无法为此找到任何功能或逻辑。用正则表达式可以这样做吗?
提前致谢
这是使用的基本 R 方法gsub:
x <- c("Peter Parker", "Hawk & Dove", "J Jonah Jameson", "3JPX spo", "Bruce Wayne")
output <- gsub("\\s+(\\S)\\S*(?!\\S)", "\\1", x, perl=TRUE)
output
[1] "PeterP" "Hawk&D" "JJJ" "3JPXs" "BruceW"
Run Code Online (Sandbox Code Playgroud)
regex 模式\s+(\S)\S*(?!\S)匹配一个或多个空格字符,然后匹配并捕获名称组件的第一个字符。它还使用名称组件的其余部分,仅替换为捕获的第一个字符。
如果您对上述内容仍然不清楚,下面是正则表达式模式的工作原理,一步一步:
\s+ match one or more space characters
(\S) then match AND capture the first character of the name-word
\S* match the remainder of the name-word
(?!\S) assert that what follows the end of the name-word is either a space
or the end of the string
Run Code Online (Sandbox Code Playgroud)
调用中的替换gsub是 just \1,它是第一个也是唯一的捕获组,对应于每个名字的第一个字母,超出了第一个名字。