如何在Swift中拆分没有分隔符的字符串

时间:2019-07-04 10:56:32

标签: arrays swift string foundation

我希望将此字符串分成4部分。到目前为止,我只能使用Before building方法对其进行拆分。但是,我也希望将components(separatedBy:)的单词分为2个部分,在那里我可以得到teamId4teamId的数字。我看过的所有解决方案始终在其中包含分隔符,例如具有空格,线条,句号等的字符串,这非常容易。我如何实现此输出4player238teamId

4

这是到目前为止的输出

var player = "player23_8_chelseaId4"

var splittedString: [String] {
    let stringArray = player.components(separatedBy: "_")
    let playerID = stringArray[0]
    let playerIndex = stringArray[1]
    let team = stringArray[2]
    // Would like "4" as the last string in the array
    let array = [playerID, playerIndex, team]
    return array
}

所需的输出为

["player23", "8", "chelseaId4"]

3 个答案:

答案 0 :(得分:2)

这是正则表达式解决方案。

在模式中,四对括号代表捕获的四个字符串,\\w+表示一个或多个单词字符。分隔符是两个下划线字符和Id字符串,其中也捕获了后者。

func splittedString(from player : String) throws -> [String] {
    var result = [String]()
    let pattern = "^(\\w+)_(\\w+)_(\\w+Id)(\\w+)$"
    let regex = try NSRegularExpression(pattern: pattern)
    if let match = regex.firstMatch(in: player, range: NSRange(player.startIndex..., in: player)) {
        for i in 1..<match.numberOfRanges {
            result.append(String(player[Range(match.range(at: i), in: player)!]))
        }
    }
    return result
}

let player = "player23_8_chelseaId4"
let splitted = try splittedString(from: player) // ["player23", "8", "chelseaId", "4"]

如果只需要chelsea而没有Id,则将模式更改为"^(\\w+)_(\\w+)_(\\w+)Id(\\w+)$"

答案 1 :(得分:1)

var player = "player23_8_chelseaId4"

var splittedString: [String] {
    let stringArray = player.components(separatedBy: "_")
    let playerID = stringArray[0]
    let playerIndex = stringArray[1]
    let team = stringArray[2]

    let temp = team.components(separatedBy: "Id")
    // Would like "4" as the last string in the array
    let array = [playerID, playerIndex,"\(temp[0])Id" , temp[1]]
    return array
}

print(splittedString) // ["player23", "8", "chelseaId", "4"]

答案 2 :(得分:0)

每个团队名称后面是否都包含“ Id”字符串?因此,您可以搜索子字符串ID并在其后剪切字符串。