我需要 Swift 3 中的一个函数,它将删除括号之间的字符串中的内容。 例如,对于像
"THIS IS AN EXAMPLE (TO REMOVE)"
这样的字符串
应该返回"THIS IS AN EXAMPLE"
我正在尝试使用
removeSubrange
方法,但我被卡住了。
最简单最短的解决方案是正则表达式:
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?
。\(
。[^)]*
。\)
。假设您只有一对括号(这只删除第一对):
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)
}
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