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

How to split a string that doesn't have a separator in Swift

我想将这个字符串分成 4 个部分。到目前为止,我只能使用 components(separatedBy:) 方法拆分它。但是我也想把最后一个词 teamId4 分成两部分,在那里我可以获得 teamId4 的数字。我看过的所有解决方案中总是包含分隔符,例如包含空格、线条、句点等的字符串,这使得它变得非常容易。我怎样才能实现这个输出 player23, 8, teamId, 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"]

所需的输出将是

["player23", "8", "chelseaId", "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]

    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"]

"Id"是每个队名后面的字符串吗?因此,您可以搜索子字符串 ID 并在其后剪切字符串。

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

pattern中4对括号代表捕获的4个字符串,\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+)$"