如何在Swift中使用正则表达式创建字符串分割扩展?

3
我编写了一个扩展程序,创建了 split 方法:
extension String {
    func split(splitter: String) -> Array<String> {
        return self.componentsSeparatedByString(splitter)
    }
}

所以在 playground 中,我可以写:

var str = "Hello, playground"

if str.split(",").count > 1{
    var out = str.split(",")[0]

    println("output: \(out)") // output: Hello
}

我需要如何才能让它像Java中的正则表达式一样工作:

str.split("[ ]+")

因为这种方式不起作用。 谢谢。

我会从这个方法开始:https://news.ycombinator.com/item?id=7890148。运行它,断开字符串直到找到的范围的开始,并一直重复此过程,直到返回“NSNotFound”。 - Alex Wayne
1个回答

10
首先,您的分割函数有些冗余。仅返回以下内容即可:
return self.componentsSeparatedByString(splitter)

其次,要使用正则表达式,只需创建一个NSRegularExpression对象,然后可能将所有出现的内容替换为您自己的“停止字符串”,最后使用该字符串进行分隔。例如:

extension String {
    func split(regex pattern: String) -> [String] {
        let template = "-|*~~*~~*|-" /// Any string that isn't contained in the original string (self).

        let regex = try? NSRegularExpression(pattern: pattern)
        let modifiedString = regex?.stringByReplacingMatches(
            in: self,
            range: NSRange(
                location: 0,
                length: count
            ),
            withTemplate: template /// Replace with the template/stop string.
        )
        
        /// Split by the replaced string.
        return modifiedString?.components(separatedBy: template) ?? []
    }
}

也许最好将Swift 5版本放在下面或作为单独的答案。 - Mundi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接