有没有办法在 R 中拆分驼峰式字符串?
我尝试过:
string.to.split = "thisIsSomeCamelCase"
unlist(strsplit(string.to.split, split="[A-Z]") )
# [1] "this" "s" "ome" "amel" "ase"
string.to.split = "thisIsSomeCamelCase"
gsub("([A-Z]){1}", " \\1", string.to.split)
# [1] "this Is Some Camel Case"
# added a counter to prevent situation mentioned in comment
strsplit(gsub("([A-Z]{1})", " \\1", string.to.split), " ")
# [[1]]
# [1] "this" "Is" "Some" "Camel" "Case"
# another attempt to meet the commenter's concern
# inserts space between lower-single upper sequence
gsub("([[:lower:]])([[:upper:]]){1}", "\\1 \\2", string.to.split)
看看 Ramnath 和我的问题,我可以说我最初的印象是这是一个未明确说明的问题,这一印象得到了支持。
并为汤米和拉曼斯的指出点赞
[:upper:]
strsplit(gsub("([[:upper:]])", " \\1", string.to.split), " ")
# [[1]]
# [1] "this" "Is" "Some" "Camel" "Case"
这是一种方法
split_camelcase <- function(...){
strings <- unlist(list(...))
strings <- gsub("^[^[:alnum:]]+|[^[:alnum:]]+$", "", strings)
strings <- gsub("(?!^)(?=[[:upper:]])", " ", strings, perl = TRUE)
return(strsplit(tolower(strings), " ")[[1]])
}
split_camelcase("thisIsSomeGood")
# [1] "this" "is" "some" "good"
这是使用单个正则表达式(Lookahead 和 Lookbehind)的方法:
strsplit(string.to.split, "(?<=[a-z])(?=[A-Z])", perl = TRUE)
## [[1]]
## [1] "this" "Is" "Some" "Camel" "Case"
这是使用
gsubfn
包的 strapply
的单行代码。正则表达式匹配字符串的开头 (^
) 后跟一个或多个小写字母 ([[:lower:]]+
) 或 (|
) 一个大写字母 ([[:upper:]]
) 后跟零个或多个小写字母([[:lower:]]*
) 并使用 c
处理匹配的字符串(将各个匹配连接成一个向量)。与 strsplit
一样,它返回一个列表,因此我们采用第一个组件 ([[1]]
) :
library(gsubfn)
strapply(string.to.split, "^[[:lower:]]+|[[:upper:]][[:lower:]]*", c)[[1]]
## [1] "this" "Is" "Camel" "Case"
我认为我的其他答案比以下更好,但如果只需要一个单线来分割......我们开始:
library(snakecase)
unlist(strsplit(to_parsed_case(string.to.split), "_"))
#> [1] "this" "Is" "Some" "Camel" "Case"
答案的开头是拆分所有字符:
sp.x <- strsplit(string.to.split, "")
然后找到哪些字符串位置是大写的:
ind.x <- lapply(sp.x, function(x) which(!tolower(x) == x))
然后用它来分割每组字符。 。 。
library(strex)
str_split_camel_case("thisIsSomeCamelCase")
# [[1]]
# [1] "this" "Is" "Some" "Camel" "Case"
这里有一个通过 Snakecase + 一些 tidyverse 助手的简单解决方案:
install.packages("snakecase")
library(snakecase)
library(magrittr)
library(stringr)
library(purrr)
string.to.split = "thisIsSomeCamelCase"
to_parsed_case(string.to.split) %>%
str_split(pattern = "_") %>%
purrr::flatten_chr()
#> [1] "this" "Is" "Some" "Camel" "Case"
Snakecase 的 Github 链接:https://github.com/Tazinho/snakecase