有没有办法在 R 中拆分驼峰字符串?
我尝试过:
string.to.split = "thisIsSomeCamelCase"
unlist(strsplit(string.to.split, split="[A-Z]") )
# [1] "this" "s" "ome" "amel" "ase"
有没有办法在 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", string.to.split)
# [1] "this Is Some Camel Case"
strsplit(gsub("([A-Z])", " \\1", string.to.split), " ")
# [[1]]
# [1] "this" "Is" "Some" "Camel" "Case"
看看 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"
这是一种使用单个正则表达式(前瞻和后瞻)的方法:
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))
然后使用它来拆分每个字符运行。. .
这是一个通过蛇盒 + 一些 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"
蛇盒的 Githublink:https ://github.com/Tazinho/snakecase