如何删除花括号及其内容(除了Swift中竖线内的内容)?

时间:2019-06-27 07:21:09

标签: ios json swift regex

我有这个字符串{bc}{sx|lineage||}{sx|ancestry||},我想删除{}及其内容,但不想删除| |内部的内容。

我尝试了以下代码,但这正在删除{}及其所有内容,包括||

"\\s?\\{.*?\\}"

2 个答案:

答案 0 :(得分:1)

如果您想完全删除{bc}并继续使用lineageancestry

let str = "{bc}{sx|lineage||}, {sx|ancestry||}"
let pattern = "\\s*\\{[^{}|]*(?:\\|([^{}|]*)\\|{2})?\\}"
let result = str.replacingOccurrences(of: pattern, with: "$1", options: .regularExpression)
print(result)   // => lineage,ancestry

请参见this regex demo

如果应该保留{bc},我建议使用

let str = "{bc}{sx|lineage||}, {sx|ancestry||}"
let pattern = "\\s*\\{[^{}|]*\\|([^{}|]*)\\|{2}\\}"
let result = str.replacingOccurrences(of: pattern, with: "$1", options: .regularExpression)
print(result)   // => {bc}lineage,ancestry

请参见regex demo

答案 1 :(得分:0)

要获取两个字符串(in your case - "|")之间的字符串,可以使用以下方法:

func getSubstringIn(_ str: String, from: String, to: String) -> String? {
    if let upperBound = str.range(of: from)?.upperBound,
        let lowerBound = str.range(of: to, range: upperBound..<str.endIndex)?.lowerBound {
        return String(str[upperBound..<lowerBound])
    }
    return nil
}

用法:

let s = getSubstringIn(test, from: "|", to: "|")

例如 字符串{bc}{sx|lineage||},将返回-lineage 和字符串{sx|ancestry||},返回-ancestry