如何在swift中从文本中提取所有电子邮件地址

ix0qys7i  于 2022-12-17  发布在  Swift
关注(0)|答案(5)|浏览(191)

我有条短信
=“+abc@gmail.com你好酷+def@gmail.com”
我想从文本中提取电子邮件地址并将其存储在数组中。我想用正则表达式来做这件事。我找到了正则表达式,但我无法将电子邮件保存到数组中。
我试过了

let regEx = "/(\\+[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9._-]+)/gi"
if let email = NSPredicate(format: "SELF MATCHES %@", regEx) {
        //what to do here
}

还是我做错了?我知道这是一个基本的问题,请帮帮忙
先谢了。

pw136qt2

pw136qt21#

这些代码对我很有效。你可以从here checkout 电子邮件正则表达式。

SWIFT 5

func extractEmailAddrIn(text: String) -> [String] {
    var results = [String]()

    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
    let nsText = text as NSString
    do {
        let regExp = try NSRegularExpression(pattern: emailRegex, options: .caseInsensitive)
        let range = NSMakeRange(0, text.count)
        let matches = regExp.matches(in: text, options: .reportProgress, range: range)

        for match in matches {
            let matchRange = match.range
            results.append(nsText.substring(with: matchRange))
        }
    } catch (let error) {
        print(error)
    }

    return results
}

SWIFT 3

func extractEmailAddrIn(text: String) -> [String] {
    var results = [String]()
    
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
    let nsText = text as NSString
    do {
        let regExp = try NSRegularExpression(pattern: emailRegex, options: NSRegularExpressionOptions.CaseInsensitive)
        let range = NSMakeRange(0, text.characters.count)
        let matches = regExp.matchesInString(text, options: .ReportProgress, range: range)
        
        for match in matches {
            let matchRange = match.range
            results.append(nsText.substringWithRange(matchRange))
        }
        
    } catch _ { 
    }
    
    return results
}
j13ufse2

j13ufse22#

我建议使用NSRegularExpression类而不是NSPredicate。正则表达式的格式来自ICU
下面是一种方法:

let pattern = "(\\+[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9._-]+)"
let regexp = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive, error: nil)

let str = "+abc@gmail.com heyyyyy cool +def@gmail.com" as NSString

var results = [String]()
regexp?.enumerateMatchesInString(str, options: NSMatchingOptions(0), range: NSRange(location: 0, length: str.length), usingBlock: { (result: NSTextCheckingResult!, _, _) in
    results.append(str.substringWithRange(result.range))
})

// Gives [+abc@gmail.com, +def@gmail.com]
nnt7mjpx

nnt7mjpx3#

看起来你的正则表达式名称是错误的。你声明它为regEx,但在你的NSPredicate中你使用了emailRegEx

rjee0c15

rjee0c154#

你需要在邮件地址里加上加号吗?

地址中没有+符号:

([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9._-]+)
结果:[”abc@gmail.com“,“def@gmail.com“]

地址中带有+号:

([\\+a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9._-]+)
结果:["+abc@gmail.com”,“+def@gmail.com”]

ippsafx7

ippsafx75#

下面是我创建的字符串扩展名,用于从中提取电子邮件它在swift 4中运行良好。

extension String {    
  func getEmails() -> [String] {
    if let regex = try? NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}", options: .caseInsensitive)
    {
        let string = self as NSString
        
        return regex.matches(in: self, options: [], range: NSRange(location: 0, length: string.length)).map {
            string.substring(with: $0.range).lowercased()
        }
    }
    return []
  }
}

用法

let test = "Precision Construction John Smith cONSTRUCTION WORKER 123 Main St, Ste. 30o 
www.precsioncontructien.com adil@gmail.com fraz@gmail.pk janesmit@precisiencenstruction.com 555.555.5SS5"
            let emails = test.getEmails()
 print(emails)

//结果[”adil@gmail.com“,“fraz@gmail.pk“,“janesmit@precisiencenstruction.com“]

相关问题