know if string is snake case in swift

To check if a string is in snake case in Swift, you can use regular expressions. Here's a function that checks if a string is in snake case:

main.swift
func isSnakeCase(_ input: String) -> Bool {
    let snakeCasePattern = "^[a-z]+(_[a-z]+)*$"
    let regex = try! NSRegularExpression(pattern: snakeCasePattern)
    let range = NSRange(location: 0, length: input.utf16.count)
    
    return regex.firstMatch(in: input, options: [], range: range) != nil
}
304 chars
8 lines

Usage:

main.swift
let string1 = "hello_world"
print(isSnakeCase(string1)) // true

let string2 = "helloWorld"
print(isSnakeCase(string2) // false
128 chars
6 lines

The isSnakeCase function uses a regular expression pattern ^[a-z]+(_[a-z]+)*$ to match the string. The pattern checks if the string starts with one or more lowercase letters, followed by zero or more groups of an underscore followed by one or more lowercase letters.

Note that this function assumes that the string only contains ASCII characters. If you need to support non-ASCII characters, you can modify the regular expression pattern accordingly.

gistlibby LogSnag