删除括号之间的子字符串

问题描述 投票:0回答:3

我需要 Swift 3 中的一个函数,它将删除括号之间的字符串中的内容。 例如,对于像

"THIS IS AN EXAMPLE (TO REMOVE)"
这样的字符串 应该返回
"THIS IS AN EXAMPLE"

我正在尝试使用

removeSubrange
方法,但我被卡住了。

swift swift3
3个回答
24
投票

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

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?
  • 左括号
    \(
  • 零个或多个字符除了右括号之外的任何字符
    [^)]*
  • 右括号
    \)

2
投票

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

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)
}

1
投票

基于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
© www.soinside.com 2019 - 2024. All rights reserved.