迅速在子字符串之间替换?

时间:2019-06-04 18:22:20

标签: swift string replace

我有一个像这样的字符串:

let someString = "The (randomcharacters)(someknowncharacters) are playing in the NBA Finals"

我想用字符串The替换字符串(someWarriors之间的所有内容。我已经研究过使用replacingOcurrences,但这并不能满足我的要求。

2 个答案:

答案 0 :(得分:1)

使用一些“ somerandomcharacters”将意味着您实际上是在使用String作为(确实很糟糕)的工具来传输多个数据。但是我们已经有了一种处理数据类型的方法。

我们可以创建一个结构,其中包含描述篮球比赛的必要信息。我们可以很容易地访问其重要组件,从而在整个应用程序中传递这些数据。只有我们的UI层需要一个字符串,因此我们只在最后一刻,即在UI层,才生成此结构的字符串描述。

struct BasketballTeam {
    var name: String
}

struct BasketballGame: CustomStringConvertible {
    let homeTeam: BasketballTeam
    let awayTeam: BasketballTeam
    let eventName: String

    var description: String {
        return "The \(homeTeam.name) are playing the \(awayTeam.name) in the \(eventName)."
    }
}

let game = BasketballGame(
    homeTeam: BasketballTeam(name: "Toronto Raptors"),
    awayTeam: BasketballTeam(name: "Golden State Warriors"),
    eventName: "NBA Finals"
)
print(game.description) // => The Toronto Raptors are playing the Golden State Warriors in the NBA Finals.

答案 1 :(得分:1)

这是另一次尝试使用replaceOccurencesOf

func replace(_ original: String, between firstPart: String, and secondPart: String, with: String ) -> String {
    let pattern = "\(firstPart) .* \(secondPart)"
    let replacement = "\(firstPart) \(with) \(secondPart)"
    return original.replacingOccurrences(of: pattern, with: replacement, options: .regularExpression)
}

在处理替换单词周围的空间方面可能需要进行一些调整。

示例

let newString = replace("The Raptors are playing in the NBA Finals", between: "The", and: "are", with: "Warriors")