在 Swift 中查找括号之间的文本 [英] Finding text between parentheses in Swift

查看:42
本文介绍了在 Swift 中查找括号之间的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取 Swift 中括号之间文本的字符串值数组?

How do you get an array of string values for the text between parentheses in Swift?

例如来自:MyFileName(2015)(Type)(createdBy).zip

我想要:[2015,Type,createdBy]

推荐答案

这里是 Swift 4.2 中的完整示例

Here is a complete example in Swift 4.2

func matchesForRegexInText(regex: String!, text: String!) -> [String] {

do {

    let regex = try NSRegularExpression(pattern: regex, options: [])
    let nsString = text as NSString

    let results = regex.matches(in: text,
                                        options: [], range: NSMakeRange(0, nsString.length))
    return results.map { nsString.substring(with: $0.range)}

} catch let error as NSError {

    print("invalid regex: \(error.localizedDescription)")

    return []
}}

和用法:

let regex = "\\((.*?)\\)"
mmatchesForRegexInText(regex: regex, text: " exmaple (android) of (qwe123) text (heart) between parentheses")

这篇关于在 Swift 中查找括号之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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