我需要一个Swift 3中的函数,它将删除括号中字符串中的内容。
例如,对于像"THIS IS AN EXAMPLE (TO REMOVE)"
这样的字符串
应该返回"THIS IS AN EXAMPLE"
我正在尝试使用removeSubrange
方法,但我被卡住了。
答案 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)
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