Swift - Splitting strings with regex - ignoring search string

前端 未结 2 1794
半阙折子戏
半阙折子戏 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: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..["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.

提交回复
热议问题