在R中拆分驼峰式大小写

aelbi1ox  于 2023-03-05  发布在  其他
关注(0)|答案(7)|浏览(127)

有没有办法在R中拆分驼峰式大小写字符串?
我曾尝试:

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

xwmevbvl1#

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的和我的,我可以说我最初的印象是这是一个未详细说明的问题得到了支持。
给予Tommy和Ramanth一张赞成票因为他们指出了[:upper:]

strsplit(gsub("([[:upper:]])", " \\1", string.to.split), " ")
# [[1]]
# [1] "this"  "Is"    "Some"  "Camel" "Case"
kiayqfof

kiayqfof2#

下面是一种方法

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"
41zrol4v

41zrol4v3#

下面是使用单个正则表达式(Lookahead和Lookbehind)的方法:

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

## [[1]]
## [1] "this"  "Is"    "Some"  "Camel" "Case"
wz1wpwve

wz1wpwve4#

下面是一个使用gsubfn包的strapply的一行程序。(^)后跟一个或多个小写字母([[:lower:]]+)或(|)大写字母([[:upper:]])后跟零个或多个小写字母([[:lower:]]*)并使用c处理匹配的字符串(它将单个匹配连接成一个向量)。与strsplit一样,它返回一个列表,因此我们取第一个组件([[1]]):

library(gsubfn)
strapply(string.to.split, "^[[:lower:]]+|[[:upper:]][[:lower:]]*", c)[[1]]
## [1] "this"  "Is"    "Camel" "Case"
yeotifhr

yeotifhr5#

我想我的另一个答案比下面的更好,但如果只需要一个线分裂...我们开始吧:

library(snakecase)
unlist(strsplit(to_parsed_case(string.to.split), "_"))
#> [1] "this"  "Is"    "Some"  "Camel" "Case"
46qrfjad

46qrfjad6#

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

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

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

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

然后用它来分割每一串字符......

bn31dyow

bn31dyow7#

这里是一个简单的解决方案,通过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"

Githublink到snakecase:https://github.com/Tazinho/snakecase

相关问题