How do I take a substring to the first index of a character?

后端 未结 3 1304
予麋鹿
予麋鹿 2021-01-24 12:42

I\'m very new to Swift; I\'ve spent the morning reading StackOverflow and trying many strategies, in vain, to accomplish the following:

I have a string, say \"12345 is

3条回答
  •  孤独总比滥情好
    2021-01-24 13:13

    You can use a regex, try this code:

    var myMessage  = "12345 is your number!"
    
    if let match = myMessage.rangeOfString("-?\\d+", options: .RegularExpressionSearch) {
    
        print(myMessage.substringWithRange(match)) // 12345
        let myNumber = Int(myMessage.substringWithRange(match)) // Then you can initialize a new variable
    }
    

    The advantage is that this method extracts only the numbers wherever they are in the String

    Hope this help ;)

提交回复
热议问题