簡體   English   中英

如何在某些字符串處停止正則表達式表達式並捕獲子字符串?

[英]How to stop regex expression at certain string and capture the sub string?

我想捕獲正則表達式的兩次匹配之間的字符串。

我有這串

var testingString="NO Lettuce nNO Onions nNO Tomato nNO Ketchup NO  Grilled Onions NO baked Sub Zapps"

我現在使用的正則表達式為:

let matches = self.regexMatches(for: "([^\\snNO]+|[NO]\\S+([a-zA-Z0-9_\\w+])+\\S)", in: testingString)

我得到的輸出為:

Lettuce
Onions
Tomato
Ketchup
Grilled
Onions
baked
sub
zapps

但我希望輸出為:

Lettuce
Onions
Tomato
Ketchup
Grilled Onions
baked sub zapps

這是我正在使用的regexMatches函數:

func regexMatches(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))
        var tempResults = results.map { result in
            (1..<result.numberOfRanges - 1).map { result.rangeAt($0).location != NSNotFound
                ? nsString.substring(with: result.rangeAt($0))
                : ""
            }
        }
        return tempResults.flatMap{$0}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

我會做得更簡單。 只需將nNONO替換為拆分字符,然后對其進行拆分。 現在,修剪空白,刪除所有空的拆分,即可完成。

let s = "NO Lettuce nNO Onions nNO Tomato nNO Ketchup NO  Grilled Onions NO baked Sub Zapps"
let pattern = "\\bn?NO\\b"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let s2 = regex.stringByReplacingMatches(in: s, options: [], range: NSRange(location: 0, length: s.utf16.count), withTemplate: "|")
let arr = s2.split(separator: "|", omittingEmptySubsequences: true)
    .map{$0.trimmingCharacters(in: .whitespaces)}
// ["Lettuce", "Onions", "Tomato", "Ketchup", "Grilled Onions", "baked Sub Zapps"]

暫無
暫無

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

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