检索swift中的substring阵列与正则匹配

发布于 2025-01-27 02:52:51 字数 1445 浏览 2 评论 0原文

有什么方法可以检索字符串中 @ sign前缀的单词数组?

“ @city == xyz和@hobby ==园艺” - > [“ @city”,“@hobby”]

我尝试了以下两种方法,但两者都返回一个空数组。

let regexp = "/@\\w*/g"

func matches(for regex: String, in text: String) -> [String] {
    do {
        let regex = try NSRegularExpression(pattern: regex)
        let results = regex.matches(in: text,range: NSRange(text.startIndex..., in: text))
        return results.map {
            String(text[Range($0.range, in: text)!])
        }
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

extension String {
    func regex (pattern: String) -> [String] {
        do {
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: 0))
            let nsstr = self as NSString
            let all = NSRange(location: 0, length: nsstr.length)
            var matches : [String] = [String]()
            regex.enumerateMatches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: all) {
                (result : NSTextCheckingResult?, _, _) in
                if let r = result {
                    let result = nsstr.substring(with: r.range) as String
                    matches.append(result)
                }
            }
            return matches
        } catch {
            return [String]()
        }
    }
}

Is there any way to retrieve an array of words prefixed with @ sign in a string?

"@City == xyz AND @Hobby == gardening" -> ["@City","@Hobby"]

I tried below two methods but both are returning an empty array.

let regexp = "/@\\w*/g"

func matches(for regex: String, in text: String) -> [String] {
    do {
        let regex = try NSRegularExpression(pattern: regex)
        let results = regex.matches(in: text,range: NSRange(text.startIndex..., in: text))
        return results.map {
            String(text[Range($0.range, in: text)!])
        }
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

extension String {
    func regex (pattern: String) -> [String] {
        do {
            let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: 0))
            let nsstr = self as NSString
            let all = NSRange(location: 0, length: nsstr.length)
            var matches : [String] = [String]()
            regex.enumerateMatches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: all) {
                (result : NSTextCheckingResult?, _, _) in
                if let r = result {
                    let result = nsstr.substring(with: r.range) as String
                    matches.append(result)
                }
            }
            return matches
        } catch {
            return [String]()
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心如荒岛 2025-02-03 02:52:51

@jnpdx在评论中暗示的那样,您的基本问题是您的regexp字符串包含来自另一种语言的控制元素。以下内容应解决您的问题:

let regexp = "@\\w*"

您还会根据Objective-C及其相关类型的转换而陷入不必要的试用语句和过时的API中。以下应该做:

func matches(for regex: String, in text: String) -> [String] {
    var result = [String]()
    var startIndex = text.startIndex
    let endIndex = text.endIndex
    while let range = text.range(of: regex,
                                 options: .regularExpression,
                                 range: startIndex ..< endIndex)
    {
        result.append(String(text[range]))
        startIndex = range.upperBound
    }
    return result
}

Your fundamental issue, as @jnpdx hinted at in a comment, is that your regexp string contains control elements from another language. The following should solve your issue:

let regexp = "@\\w*"

You also get bogged down in unnecessary try-catch statements and outdated APIs based on Objective-C and their related type conversions. The following should do:

func matches(for regex: String, in text: String) -> [String] {
    var result = [String]()
    var startIndex = text.startIndex
    let endIndex = text.endIndex
    while let range = text.range(of: regex,
                                 options: .regularExpression,
                                 range: startIndex ..< endIndex)
    {
        result.append(String(text[range]))
        startIndex = range.upperBound
    }
    return result
}
内心旳酸楚 2025-02-03 02:52:51

iOS 16+上,您也可以这样写。

let text = "@City == xyz AND @Hobby == gardening"
let regex = /@\w*/

let matches = text.matches(of: regex)
let results = matches.map { String($0.output) }

print(results) // ["@City", "@Hobby"]

On iOS 16+ you can also write like this.

let text = "@City == xyz AND @Hobby == gardening"
let regex = /@\w*/

let matches = text.matches(of: regex)
let results = matches.map { String($0.output) }

print(results) // ["@City", "@Hobby"]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文