-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsnake_case.rs
60 lines (51 loc) · 1.93 KB
/
snake_case.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//! Converts `String` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
//!
//! Example
//! ```
//! use lodash_rust::snake_case;
//!
//! let value = String::from("Foo Bar");
//! let res = snake_case::new(&value);
//! println!("{res}") // "foo-bar"
//! ```
extern crate regex;
pub fn new(s: &str) -> String {
let re = regex::Regex::new("[^a-zA-Z0-9]+").unwrap();
let result = re.replace_all(s, " ");
let result = result.trim();
let underscore = "_";
let result_string = re.replace_all(result, underscore);
// check if string contains "_"
let re2 = regex::Regex::new(format!("[{underscore}]+").as_str()).unwrap();
let contains_underscore = re2.is_match(result_string.as_ref());
// check if contains numbers
let re3 = regex::Regex::new("[0-9]+").unwrap();
let contains_number = re3.is_match(result_string.as_ref());
let mut build_result_string = String::new();
if !contains_underscore | contains_number {
let mut tmp = [0u8; 4];
// convert to char
let characters: Vec<char> = result_string.chars().collect();
for letter in characters {
if letter.is_uppercase() {
build_result_string.push_str(underscore);
build_result_string.push_str(letter.encode_utf8(&mut tmp));
} else if letter.is_numeric() {
build_result_string.push_str(underscore);
build_result_string.push_str(letter.encode_utf8(&mut tmp));
build_result_string.push_str(underscore);
} else {
build_result_string.push_str(letter.encode_utf8(&mut tmp));
}
}
return build_result_string.to_lowercase();
}
result_string.to_string().to_lowercase()
}
#[test]
fn test_new() {
assert_eq!(new("Foo Bar"), "foo_bar");
assert_eq!(new("fooBar"), "foo_bar");
assert_eq!(new("__FOO_BAR__"), "foo_bar");
assert_eq!(new("foo2bar"), "foo_2_bar");
}