Reputation: 860
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
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:
\s?
.\(
.[\w\s]*
.\)
.Alternative pattern is #"\s?\([^)]*\)"#
which represents:
\s?
.\(
.[^)]*
.\)
.Upvotes: 25
Reputation: 25294
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
Upvotes: 1
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