Swift - Splitting strings with regex - ignoring search string

前端 未结 2 1714
半阙折子戏
半阙折子戏 2021-01-13 15:55

There is a clever 1st answer given here for splitting swift string with a regex expression

split string answer

However it keeps the searched text within the

相关标签:
2条回答
  • 2021-01-13 16:42

    My suggestion is to create an UUID string as separator, then replace the occurrences of the regex pattern with this UUID string and split the string.

    let string = "hi|thisZshouldZYbe|separated"
    let uuid = UUID().uuidString
    let result = string.replacingOccurrences(of: "\\||ZY?", with: uuid, options: .regularExpression).components(separatedBy: uuid)
    

    Your pattern works only in another order of the OR parts ("\\||ZY|Z")

    0 讨论(0)
  • 2021-01-13 16:53

    You can define an extension like this:

    extension String {
        func split(usingRegex pattern: String) -> [String] {
            //### Crashes when you pass invalid `pattern`
            let regex = try! NSRegularExpression(pattern: pattern)
            let matches = regex.matches(in: self, range: NSRange(0..<utf16.count))
            let ranges = [startIndex..<startIndex] + matches.map{Range($0.range, in: self)!} + [endIndex..<endIndex]
            return (0...matches.count).map {String(self[ranges[$0].upperBound..<ranges[$0+1].lowerBound])}
        }
    }
    
    let str = "hi|thisZshouldZYbe|separated"
    let separator = "\\||ZY?"
    let result = str.split(usingRegex: separator)
    print(result) //->["hi", "this", "should", "be", "separated"]
    

    The above code does not work as you expect when you use "\\||Z|ZY", but I think you can modify your pattern to fit into this extension.

    0 讨论(0)
提交回复
热议问题