gpt4 book ai didi

r - R中大写和小写字符之间的字符串拆分?

转载 作者:行者123 更新时间:2023-12-02 13:12:30 25 4
gpt4 key购买 nike

我有一个字符串向量:

v1 <- c("Firstname LastnameFirstname Lastname", 
"Firstname Lastname",
"Firstname Lastname",
"Firstname LastnameFirstname Lastname")

我想将字符串拆分为小写字母和大写字母,并保留这两个字母。

期望的输出是:

[1] "Firstname Lastname" "Firstname Lastname"   "Firstname Lastname"  "Firstname Lastname"  "Firstname Lastname" "Firstname Lastname"

以下 StackExchange 中的示例我已尝试使用 gsubstrsplit 函数:

unlist(strsplit( gsub("([a-z][A-Z])","\\1~",v1), "~" ))

但这不会在字符之间分割,而是在分割点的正则表达式匹配之后分割:

[1] "Firstname LastnameF" "irstname Lastname"   "Firstname Lastname"  "Firstname Lastname"  "Firstname LastnameF" "irstname Lastname"  

如何在保留两个字符的情况下拆分字符?

最佳答案

我们可以使用正则表达式环视来匹配小写字母(正向查找 - (?<=[a-z]) ),然后是大写字母(正向查找 - (?=[A-Z]) )

unlist(strsplit(v1, "(?<=[a-z])(?=[A-Z])", perl = TRUE))
#[1] "Firstname Lastname" "Firstname Lastname" "Firstname Lastname"
#[4] "Firstname Lastname" "Firstname Lastname" "Firstname Lastname"

关于r - R中大写和小写字符之间的字符串拆分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com