知道Swift中第一个和最后一个字符的字符串中的子串

时间:2017-05-02 16:22:01

标签: swift string

有这样的字符串:

let str = "In 1273, however, they lost their son in an accident;[2] the young Theobald was dropped by his nurse over the castle battlements.[3]"

我正在寻找一种解决方案,删除方括号的所有外观以及它之间的任何东西。

我正在尝试使用String的方法:replacingOccurrences(of:with:),但它需要删除所需的确切子字符串,所以它对我不起作用。

2 个答案:

答案 0 :(得分:4)

您可以使用:

let updated = str.replacingOccurrences(of: "\\[[^\\]]+\\]", with: "", options: .regularExpression)

正则表达式(没有Swift字符串中所需的转义符:

\[[^\]+]\]

\[\]查找字符[]。他们有一个反斜杠来删除正则表达式中这些字符的正常特殊含义。

[^]]表示匹配除]字符以外的任何字符。 +表示匹配1或更多。

答案 1 :(得分:1)

您可以创建一个while循环来获取第一个字符串范围的lowerBound和第二个字符串范围的upperBound,并从中创建一个范围。接下来只删除字符串的子范围,并为搜索设置新的startIndex。

var str = "In 1273, however, they lost their son in an accident;[2] the young Theobald was dropped by his nurse over the castle battlements.[3]"

var start = str.startIndex

while let from = str.range(of: "[", range: start..<str.endIndex)?.lowerBound,
    let to = str.range(of: "]", range: from..<str.endIndex)?.upperBound,
    from != to {
        str.removeSubrange(from..<to)
        start = from
}

print(str)   // "In 1273, however, they lost their son in an accident; the young Theobald was dropped by his nurse over the castle battlements."