簡體   English   中英

快速使用正則表達式提取和打印字符串

[英]Extract and print strings using regex in 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))")
   

將您的固定正則表達式與此解決方案相結合

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM