首页 > 解决方案 > 使用正则表达式或其他方法 Swift 在字符串中的模式中查找字符串模式

问题描述

我正在寻找一种方法来识别字符模式中的字符模式并删除模式的任何内部示例(如果存在),只留下外部示例。

一个例子是:

str = "some text [outer part [inner part] back to outer part] more text"

我想删除内部模式[ ] 离开:

str = "some text [outer part inner part back to outer part] more text"

这并不总是这种格式。还可以看到:

 str = "this text [does does no need inner brackets removed] as there aren't any"

 str = "this text [does does not]  need inner brackets [removed] as there aren't any"

 str = "this text [has one [instance] of inner brackets] and another [that is] okay"

注意:如果不同的打开和关闭分隔符是一个问题,我可以将它们更改为一个分隔符,例如 * 但我仍然想摆脱内部分隔符。

这看起来很简单,但事实证明比我预期的要难,因为 str_replace 不能自然地检测到哪个是外部的,哪个是内部的。例如,在下面我可以找到字符 [ 但不知道如果它在另一个 [...

let string = "some text [outer part [inner part] back to outer part] more text"

if string.range(of: "[\b(?=.*[)[a-zA-Z]{1,8}\b", options: [.regularExpression, caseInsensitive]) != nil {
print("found a match")
} else {
print("no match present")
}

感谢您的任何建议。

标签: iosswiftstr-replace

解决方案


您可以找到右括号的第一个索引,然后搜索左括号的最后一个索引直到该索引。然后,您可以检查前后的子字符串是否有左括号和右括号:

extension StringProtocol where Self: RangeReplaceableCollection {
    mutating func removeInnerBrackets() {
        if let close = firstIndex(of: "]"),
            let open = self[..<close].lastIndex(of: "["),
            let _ = self[..<open].firstIndex(of: "["),
            let _ =  self[index(after: close)...].firstIndex(of: "]") {
            remove(at: close)
            remove(at: open)
        }
    }
}

var sentence = "some text [outer [part [inner part] back to outer] part] more text"
sentence.removeInnerBrackets()
sentence // "some text [outer [part inner part back to outer] part] more text"

推荐阅读