我希望在符号@或swift中的数字之前获取值。我的电子邮件是do {
//Convert to Data
let jsonData = try JSONSerialization.data(withJSONObject: dictionaryArray, options: JSONSerialization.WritingOptions.prettyPrinted)
//Do this for print data only otherwise skip
if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
print(JSONString)
}
//In production, you usually want to try and cast as the root data structure. Here we are casting as a dictionary. If the root object is an array cast as [AnyObject].
var json = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: AnyObject]
} catch {
print(error.description)
}
。我只想获得john@gmail.com
。另一个例子是john
。我只想获得peter34@gmail.com
。
答案 0 :(得分:1)
使用components(separatedBy:)
传递CharacterSet
由@
和数字组成,然后使用first
获取符号的第一部分:
let emails = ["john@gmail.com", "peter34@gmail.com"]
for email in emails {
if let name = email.components(separatedBy: CharacterSet(charactersIn: ("@0123456789"))).first {
print(name)
}
}
输出:
john peter
答案 1 :(得分:-2)
试试这个
let EMAIL= "peter34@gmail.com"
let EMAILARR= EMAIL.characters.split{$0 == "@"}.map(String.init)
EMAILARR[0] // to get peter34
EMAILARR[1] // to get gmail.com