2017-08-11 170 views
1

我想從我的字符串得到具體的人物,像這樣的例子獲取特定的字符範圍從字符串SWIFT 3

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

// Without doing this 
var theCharactersIWantFromTheString = "@steve123" 

我怎麼會只檢索海峽

的@ steve123
+0

你最好弄清楚你的要求。範圍始終以'@'開始?或者一些角色可以繼續使用'@'?然後字母(1+或0+?)跟着然後數字?或者字母和數字可以以任意順序出現?或者一些有限的符號可以混合使用? – OOPer

+0

我只想要@symbol和albetical字符 – user8426652

+0

您通常不會在_alphabetical characters_中包含數字。但你的例子有數字'123'。請澄清。 – OOPer

回答

7

你可以使用正則表達式"\\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" 
} 
相關問題