首页 > 解决方案 > 在 swift 中使用正则表达式提取和打印字符串

问题描述

我希望在正则表达式上使用 swift 提取和打印字符串,但我一直坚持如何去做。我是 swift 和 swift 上的正则表达式的新手,所以很难弄清楚

在下面的示例中,我想打印 62AD 和 21BC(方括号内的任何内容)。我只能想出这段代码,但这不会提取任何东西并给出一个 nil 值。换行符和引号是字符串的一部分

let output = "\"Living Room\" [62AD]\n Hub \"Living Room\" [21BC]:"
let range = NSRange(output.startIndex..<output.endIndex,in: output)
let patternToMatch1 = "\"Living Room\" [.*]+\n"
let patternToMatch2 = "Hub \"Living Room\" [^:]+:"
let captureRegex1 = try! NSRegularExpression(pattern: patternToMatch1, options: [])
let captureRegex2 = try! NSRegularExpression(pattern: patternToMatch2, options: [])
let matches1 = captureRegex1.matches(in: output,options: [],range: range)
guard let match1 = matches1.first else {
         throw NSError(domain: "", code: 0, userInfo: nil)
}
print("\(String(describing:match1))")

let matches2 = captureRegex2.matches(in: output,options: [],range: range)
guard let match2 = matches2.first else {
         throw NSError(domain: "", code: 0, userInfo: nil)
}
print("\(String(describing:match2))")
   

标签: iosswiftregex

解决方案


将您的固定正则表达式与此解决方案相结合:

import Foundation
func matches(for regex: String, in text: String) -> [String] {
    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        return results.map { nsString.substring(with: $0.range(at: 1))}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}
let output = "\"Living Room\" [62AD]\n Hub \"Living Room\" [21BC]:"
let patternToMatch1 = "\"Living Room\"\\s*\\[(.*?)]"
print(matches(for: patternToMatch1, in:output))

结果["62AD", "21BC"]

请参阅正则表达式证明

解释

--------------------------------------------------------------------------------
  "Living Room"            '"Living Room"'
--------------------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \[                       '['
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  ]                        ']'

推荐阅读