Rebol3 Code Examplex
Camel case and snake case
Convert identifiers between camelCase and snake_case.
Rebol [
title: "Rosetta code: Camel case and snake case"
file: %Camel_case_and_snake_case.r3
url: https://rosettacode.org/wiki/Camel_case_and_snake_case
]
cammel-case-split: function/with [
"Split a camelCase string into a block of words"
input [string!]
][
parse/case input [
collect any [
[
ahead upper s: skip [to upper | to end] e:
| end reject
| s: [to upper | to end] e:
] keep ( copy/part s e )
]
]
][ upper: charset [#"A" - #"Z"] ]
to-snake-case: function[
"Convert a string to snake_case"
input [string!]
][
out: lowercase ajoin/with cammel-case-split input #"_"
div: charset " -_"
parse trim/head/tail out [any [to div change some div #"_"]]
out
]
to-camel-case: function[
"Convert a string to camelCase"
input [string!]
][
out: copy ""
foreach p split input charset " _-" [
append out uppercase/part p 1
]
lowercase/part out 1
out
]
tests: [
"snakeCase"
"snake_case"
"variable_10_case"
"variable10Case"
"ɛrgo rE tHis"
"hurry-up-joe!"
"c://my-docs/happy_Flag-Day/12.doc"
" spaces "
]
print " === To snake_case ==="
foreach test tests [
printf [-35 " --> " ][mold test mold to-snake-case test]
]
print ""
print " === To camelCase ==="
foreach test tests [
printf [-35 " --> " ][mold test mold to-camel-case test]
]
Output:
=== To snake_case ===
"snakeCase" --> "snake_case"
"snake_case" --> "snake_case"
"variable_10_case" --> "variable_10_case"
"variable10Case" --> "variable10_case"
"ɛrgo rE tHis" --> "ɛrgo_r_e_t_his"
"hurry-up-joe!" --> "hurry_up_joe!"
"c://my-docs/happy_Flag-Day/12.doc" --> "c://my_docs/happy_flag_day/12.doc"
" spaces " --> "spaces"
=== To camelCase ===
"snakeCase" --> "snakeCase"
"snake_case" --> "snakeCase"
"variable_10_case" --> "variable10Case"
"variable10Case" --> "variable10Case"
"ɛrgo rE tHis" --> "ɛrgoRETHis"
"hurry-up-joe!" --> "hurryUpJoe!"
"c://my-docs/happy_Flag-Day/12.doc" --> "c://myDocs/happyFlagDay/12.doc"
" spaces " --> "spaces"