sski
sski

Reputation: 860

Remove substring between parentheses

I need a function in Swift 3 which will remove content in a string between parentheses. E.g for a string like "THIS IS AN EXAMPLE (TO REMOVE)" should return "THIS IS AN EXAMPLE"

I'm trying to use removeSubrange method but I'm stuck.

Upvotes: 5

Views: 6635

Answers (3)

vadian
vadian

Reputation: 285072

Most simple Shortest solution is regular expression:

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

The pattern searches for:

  • An optional whitespace character \s?.
  • An opening parenthesis \(.
  • Zero or more word or whitespace characters [\w\s]*.
  • A closing parenthesis \).

Alternative pattern is #"\s?\([^)]*\)"# which represents:

  • An optional whitespace character \s?.
  • An opening parenthesis \(.
  • Zero or more characters anything but a closing parenthesis [^)]*.
  • A closing parenthesis \).

Upvotes: 25

Vasily  Bodnarchuk
Vasily Bodnarchuk

Reputation: 25294

Based on vadian answer

Details

  • swift 4.2
  • Xcode 10.1 (10B61)

Solution

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

Usage

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

Results

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

Upvotes: 1

BallpointBen
BallpointBen

Reputation: 13760

Assuming you'll only have one pair of parentheses (this only removes the first pair):

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

Upvotes: 2

Related Questions