12

有没有办法在 R 中拆分驼峰字符串?

我尝试过:

string.to.split = "thisIsSomeCamelCase"
unlist(strsplit(string.to.split, split="[A-Z]") )
# [1] "this" "s"    "ome"  "amel" "ase" 
4

7 回答 7

14
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" 
于 2011-12-06T21:26:41.210 回答
11

这是一种方法

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"
于 2011-12-06T21:24:01.663 回答
7

这是一种使用单个正则表达式(前瞻和后瞻)的方法:

strsplit(string.to.split, "(?<=[a-z])(?=[A-Z])", perl = TRUE)

## [[1]]
## [1] "this"  "Is"    "Some"  "Camel" "Case" 
于 2015-04-11T02:09:53.720 回答
2

这是使用gsubfn包的strapply. 正则表达式匹配字符串的开头 ( ^) 后跟一个或多个小写字母 ( [[:lower:]]+) 或 ( |) 一个大写字母 ( [[:upper:]]) 后跟零个或多个小写字母 ( [[:lower:]]*) 并使用c(连接单个匹配成向量)。因为strsplit它返回一个列表,所以我们采用第一个组件 ( [[1]]) :

library(gsubfn)
strapply(string.to.split, "^[[:lower:]]+|[[:upper:]][[:lower:]]*", c)[[1]]
## [1] "this"  "Is"    "Camel" "Case" 
于 2011-12-06T22:08:15.730 回答
1

我认为我的另一个答案比以下答案更好,但如果只需要一个分割线......我们开始吧:

library(snakecase)
unlist(strsplit(to_parsed_case(string.to.split), "_"))
#> [1] "this"  "Is"    "Some"  "Camel" "Case" 
于 2017-03-27T09:55:37.947 回答
0

答案的开头是拆分所有字符:

sp.x <- strsplit(string.to.split, "")

然后找出哪些字符串位置是大写的:

ind.x <- lapply(sp.x, function(x) which(!tolower(x) == x))

然后使用它来拆分每个字符运行。. .

于 2011-12-06T21:26:46.143 回答
-1

这是一个通过蛇盒 + 一些 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

于 2017-03-25T22:16:01.240 回答