Search code examples
swiftregexregex-groupregex-greedynsregularexpression

Regular expressions in swift


I'm bit confused by NSRegularExpression in swift, can any one help me?

task:1 given ("name","john","name of john")
then I should get ["name","john","name of john"]. Here I should avoid the brackets.

task:2 given ("name"," john","name of john")
then I should get ["name","john","name of john"]. Here I should avoid the brackets and extra spaces and finally get array of strings.

task:3 given key = value // comment
then I should get ["key","value","comment"]. Here I should get only strings in the line by avoiding = and //
I have tried below code for task 1 but not passed.

let string = "(name,john,string for user name)"
let pattern = "(?:\\w.*)"

do {
    let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))
    for match in matches {
        if let range = Range(match.range, in: string) {
            let name = string[range]
            print(name)
        }
    }
} catch {
    print("Regex was bad!")
}


Thanks in advance.


Solution

  • Separate the string by non alpha numeric characters except white spaces. Then trim the elements with white spaces.

    extension String {
        func words() -> [String] {
            return self.components(separatedBy: CharacterSet.alphanumerics.inverted.subtracting(.whitespaces))
                    .filter({ !$0.isEmpty })
                    .map({ $0.trimmingCharacters(in: .whitespaces) })
        }
    }
    
    let string1 = "(name,john,string for user name)"
    let string2 = "(name,       john,name of john)"
    let string3 = "key = value // comment"
    
    print(string1.words())//["name", "john", "string for user name"]
    print(string2.words())//["name", "john", "name of john"]
    print(string3.words())//["key", "value", "comment"]