How to check if a string contains only letters, numbers, underscores and dashes in Swift

1 Answer

0 votes
import Foundation

func isValidString(_ s: String) -> Bool {
    let pattern = "^[A-Za-z0-9_-]*$"

    guard let regex = try? NSRegularExpression(pattern: pattern) else {
        return false
    }

    let range = NSRange(location: 0, length: s.utf16.count)
    
    return regex.firstMatch(in: s, options: [], range: range) != nil
}

let s1 = "-abc_123-"
print(isValidString(s1) ? "yes" : "no")

let s2 = "-abc_123-(!)"
print(isValidString(s2) ? "yes" : "no")


 
 
/*
run:
 
yes
no

*/

 



answered May 31, 2025 by avibootz
...