从字符串swift获取特定范围的字符3

use*_*652 1 ios swift swift3

我想从我的字符串中获取特定字符,例如这样

var str = "hey steve @steve123, you would love this!"

// Without doing this
var theCharactersIWantFromTheString = "@steve123"
Run Code Online (Sandbox Code Playgroud)

我怎样才能从str中检索@ steve123

Leo*_*bus 8

您可以使用正则表达式"\\B\\@\\w+".

let pattern = "\\B\\@\\w+"
let sentence = "hey steve @steve123, you would love this!"

if let range = sentence.range(of: pattern, options: .regularExpression) {
    print(sentence.substring(with: range))  // "@steve123\n"
}
Run Code Online (Sandbox Code Playgroud)