How to convert CamelCase to not.camel.case in R

后端 未结 3 1346
鱼传尺愫
鱼传尺愫 2020-12-16 21:32

In R, I\'d like to convert

c(\"ThisText\", \"NextText\")

to

c(\"this.text\", \"next.text\")

This is the r

相关标签:
3条回答
  • 2020-12-16 22:07

    You can replace all capitals with themselves and a preceeding dot with gsub, change everything tolower, and the substr out the initial dot:

    x <- c("ThisText", "NextText", "LongerCamelCaseText")
    
    substr(tolower(gsub("([A-Z])","\\.\\1",x)),2,.Machine$integer.max)
    [1] "this.text"              "next.text"              "longer.camel.case.text"
    
    0 讨论(0)
  • 2020-12-16 22:11

    You could do this also via the snakecase package:

    install.packages("snakecase")
    library(snakecase)
    
    to_snake_case(c("ThisText", "NextText"), sep_out = ".")
    # [1] "this.text" "next.text"
    

    Github link to package: https://github.com/Tazinho/snakecase

    0 讨论(0)
  • 2020-12-16 22:18

    Not clear what the entire set of rules is here but we have assumed that

    • we should lower case any upper case character after a lower case one and insert a dot between them and also
    • lower case the first character of the string if succeeded by a lower case character.

    To do this we can use perl regular expressions with sub and gsub:

    # test data
    camelCase <-  c("ThisText", "NextText", "DON'T_CHANGE")
    
    
    s <- gsub("([a-z])([A-Z])", "\\1.\\L\\2", camelCase, perl = TRUE)
    sub("^(.[a-z])", "\\L\\1", s, perl = TRUE) # make 1st char lower case
    

    giving:

    [1] "this.text"    "next.text"    "DON'T_CHANGE"
    
    0 讨论(0)
提交回复
热议问题