Swift - 使用正则表达式拆分字符串 - 忽略搜索字符串 [英] Swift - Splitting strings with regex - ignoring search string

查看:47
本文介绍了Swift - 使用正则表达式拆分字符串 - 忽略搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里给出了一个聪明的第一个答案,用于使用正则表达式拆分 swift 字符串

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

拆分字符串答案

但是它将搜索的文本保留在答案数组中.我正在尝试做类似的事情,但忽略充当分隔符的字符(例如,就像 swift split 函数一样,但只是使用正则表达式作为分隔符).

However it keeps the searched text within the array of answers. I'm trying to do a similar thing, but ignoring the characters acting as separators (e.g. just like the swift split function, but just with a regex expression as the separator).

例如:正则表达式类似于

As an example: regex would be something like

"\\\||Z|ZY"

并且当应用于 "hi|thisZshouldZYbe|separated" 字符串时,您将返回一个数组

and when applied to string of "hi|thisZshouldZYbe|separated" then you would get back an array

["hi", "this", "should", "be", "separated"]

注意.正则表达式适用于带有双重转义的 swift NSRegularExpression 格式.在常规正则表达式中,它只是 "\||Z|ZY"另外注意正则表达式包含垂直线符号而不是字母l"

NB. The regex is adapted to the swift NSRegularExpression format with the double escape. In regular regex it would just be "\||Z|ZY" Also NB the regex contains the vertical line symbol not the letter "l"

您可能不需要对原作进行太多调整即可工作.

You prob don't need to do too many tweaks to the original to make work.

推荐答案

你可以像这样定义一个扩展:

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"]

当您使用 "\\||Z|ZY" 时,上述代码无法正常工作,但我认为您可以修改您的模式以适应此扩展.

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.

这篇关于Swift - 使用正则表达式拆分字符串 - 忽略搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆