Home > Software engineering >  how to separate secondary string from main string by swift macos?
how to separate secondary string from main string by swift macos?

Time:10-02

I need to separate the substring bc from the main string, but the result is returned: bc,d,e,f

let tokenx = "123 abc,d,e,f,"
let regex = try NSRegularExpression(pattern: "a(.*),")
let matches = regex.matches(in: tokenx, range: NSRange(tokenx.startIndex..., in: tokenx))
for match in matches {
    let swiftRange = Range(match.range(at: 1), in: tokenx)!
    print(tokenx[swiftRange])
}

CodePudding user response:

To separate anything between the a and the first comma you have to search for one or more characters which are not a comma inside the parentheses ([^,] )

let tokenx = "123 abc,d,e,f,"
let regex = try NSRegularExpression(pattern: "a([^,] )")
let matches = regex.matches(in: tokenx, range: NSRange(tokenx.startIndex..., in: tokenx))
for match in matches {
    let swiftRange = Range(match.range(at: 1), in: tokenx)!
    print(tokenx[swiftRange])
}

A more specific pattern is "a([^,] ),d,e,f,"

  • Related