@@ -85,7 +85,7 @@ str_to_camel <- function(string, first_upper = FALSE) {
8585 string <- string | >
8686 to_words() | >
8787 str_to_title() | >
88- str_remove_all(pattern = " \\ s+ " )
88+ str_remove_all(pattern = fixed( " " ) )
8989
9090 if (! first_upper ) {
9191 str_sub(string , 1 , 1 ) <- str_to_lower(str_sub(string , 1 , 1 ))
@@ -97,26 +97,35 @@ str_to_camel <- function(string, first_upper = FALSE) {
9797# ' @rdname str_to_camel
9898str_to_snake <- function (string ) {
9999 check_character(string )
100- string | >
101- to_words() | >
102- str_replace_all(pattern = " \\ s+" , replacement = " _" )
100+ to_separated_case(string , sep = " _" )
103101}
104102# ' @export
105103# ' @rdname str_to_camel
106104str_to_kebab <- function (string ) {
107105 check_character(string )
108- string | >
109- to_words() | >
110- str_replace_all(pattern = " \\ s+" , replacement = " -" )
106+ to_separated_case(string , sep = " -" )
107+ }
108+
109+ to_separated_case <- function (string , sep ) {
110+ out <- to_words(string )
111+ str_replace_all(out , fixed(" " ), sep )
111112}
112113
113114to_words <- function (string ) {
114- string | >
115- str_replace_all(" ([a-z])([A-Z])" , " \\ 1 \\ 2" ) | >
116- str_replace_all(" ([a-zA-Z])([0-9])" , " \\ 1 \\ 2" ) | >
117- str_replace_all(" ([0-9])([a-zA-Z])" , " \\ 1 \\ 2" ) | >
118- str_replace_all(" ([A-Z]+)([A-Z][a-z])" , " \\ 1 \\ 2" ) | >
119- str_to_lower() | >
120- str_replace_all(pattern = " [:punct:]" , replacement = " " ) | >
121- str_trim()
115+ breakpoints <- paste(
116+ # non-word characters
117+ " [^\\ p{L}\\ p{N}]+" ,
118+ # lowercase followed by uppercase
119+ " (?<=\\ p{Ll})(?=\\ p{Lu})" ,
120+ # letter followed by number
121+ " (?<=\\ p{L})(?=\\ p{N})" ,
122+ # number followed by letter
123+ " (?<=\\ p{N})(?=\\ p{L})" ,
124+ # uppercase followed uppercase then lowercase (i.e. end of acronym)
125+ " (?<=\\ p{Lu})(?=\\ p{Lu}\\ p{Ll})" ,
126+ sep = " |"
127+ )
128+ out <- str_replace_all(string , breakpoints , " " )
129+ out <- str_to_lower(out )
130+ str_trim(out )
122131}
0 commit comments