While I have looked at other SO questions, none have what I needed. I have a string: var match = "Match Between Bob and Mike
. I am trying to get Bob
into the Player1
variable and Mike
into the Player2
variable. Unlike other programming languages, there is no .substript
method, so I tried this:
extension StringProtocol {
func index<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> Index? {
range(of: string, options: options)?.lowerBound
}
func endIndex<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> Index? {
range(of: string, options: options)?.upperBound
}
func indices<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Index] {
ranges(of: string, options: options).map(\.lowerBound)
}
func ranges<S: StringProtocol>(of string: S, options: String.CompareOptions = []) -> [Range<Index>] {
var result: [Range<Index>] = []
var startIndex = self.startIndex
while startIndex < endIndex,
let range = self[startIndex...]
.range(of: string, options: options) {
result.append(range)
startIndex = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return result
}
}
if let index = match.endIndex(of: "Between: ") {
let substring = match[..<index] // ab
let string = String(substring)
print(string) // "ab\n"
}
It is only giving me Match Between:
and nothing else. I still need to get the rest of the statement and assign the variables. How would I do this?
CodePudding user response:
So, String
in Swift is ... complicated, for good reasons. Having said that, if you're any good with regular expression (and I'm not), you could make use of the inbuilt support in Swift 5.7
var text = "Match Between: Bob and Mike"
let regex = /Match Between: (?<player1>\w ) and (?<player2>\w )/
if let match = text.firstMatch(of: regex) {
print(match.player1)
print(match.player2)
}
Which outputs:
Bob
Mike
See Getting Started with Swift Regex for (much better) details