删除括号之间的子字符串

时间:2017-03-20 20:48:14

标签: swift swift3

我需要一个Swift 3中的函数,它将删除括号中字符串中的内容。 例如,对于像"THIS IS AN EXAMPLE (TO REMOVE)"这样的字符串 应该返回"THIS IS AN EXAMPLE"

我正在尝试使用removeSubrange方法,但我被卡住了。

3 个答案:

答案 0 :(得分:8)

最简单的最短的解决方案是正则表达式:

let string = "This () is a test string (with parentheses)"
let trimmedString = string.replacingOccurrences(of: "\\s?\\([\\w\\s]*\\)", with: "", options: .regularExpression)

模式搜索:

  • 可选的空格字符\\s?
  • 左括号\\(
  • 零个或多个单词或空格字符[\\w\\s]*
  • 右括号\\)

替代模式是"\\s?\\([^)]*\\)",代表:

  • 可选的空格字符\\s?
  • 左括号\\(
  • 零个或多个字符除右括号外的任何字符 [^)]*
  • 右括号\\)

答案 1 :(得分:0)

假设您只有一对括号(这只删除了第一对):

let s = "THIS IS AN EXAMPLE (TO REMOVE)"
if let leftIdx = s.characters.index(of: "("),
    let rightIdx = s.characters.index(of: ")")
{   
    let sansParens = String(s.characters.prefix(upTo: leftIdx) + s.characters.suffix(from: s.index(after: rightIdx)))
    print(sansParens)
}

答案 2 :(得分:0)

基于vadian答案

详细信息

  • 迅速4.2
  • Xcode 10.1(10B61)

解决方案

extension String {
    private func regExprOfDetectingStringsBetween(str1: String, str2: String) -> String {
        return "(?:\(str1))(.*?)(?:\(str2))"
    }

    func replacingOccurrences(from subString1: String, to subString2: String, with replacement: String) -> String {
        let regExpr = regExprOfDetectingStringsBetween(str1: subString1, str2: subString2)
        return replacingOccurrences(of: regExpr, with: replacement, options: .regularExpression)
    }
}

用法

let text = "str1 str2 str3 str str1 str4 str5 str1 str1 str6 str1 srt7"
print(text)
print(text.replacingOccurrences(from: "str1", to: "str1", with: "_"))

结果

// str1 str2 str3 str str1 str4 str5 str1 str1 str6 str1 srt7
// _ str4 str5 _ str6 str1 srt7