Splitting a string at a number

Say I have a string "Chris1", I want to create a substring "Chris".

In Python I would use regular expressions to split a string or to create groups of substrings.


How would I do so in Swift?


Thank you.

Accepted Reply

You can use regular expressions in Swift, explicitly use NSRegularExpression or some methods takes String.CompareOptions and you can speciy .regularExpression .

But, generally, you need to write more code to manipulate Strings in Swift than in Python.


let str = "Chris1"
var result = str
if let range = str.range(of: "[0-9]+", options: .regularExpression) {
    result = String(str[..<range.lowerBound])
}
print(result) //-> Chris

Replies

You can use regular expressions in Swift, explicitly use NSRegularExpression or some methods takes String.CompareOptions and you can speciy .regularExpression .

But, generally, you need to write more code to manipulate Strings in Swift than in Python.


let str = "Chris1"
var result = str
if let range = str.range(of: "[0-9]+", options: .regularExpression) {
    result = String(str[..<range.lowerBound])
}
print(result) //-> Chris