1

I'm trying to make a regular expression that looks for an e-mail. Everything works . How to get a Bool variable that would mean whether such an expression was found or not?

let someString = "123milka@yandex.ru123"

let regexp = "([a-zA-Z]{1,20})@([a-zA-Z]{1,20}).(com|ru|org)"

if let range = someString.range(of: regexp, options: .regularExpression) {
    let result : String = someString.substring(with: range)

    print(result)
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
NeoGeniy
  • 21
  • 5
  • FYI - your regular expression will match `===hello@example.com====` or any other email address with garbage at either end. – rmaddy Feb 22 '18 at 18:48
  • Also note that your regular expression will not match the example email address in your question. You might also want to consider using data detectors if you want to detect email addresses within a string. – rmaddy Feb 22 '18 at 19:11
  • If this is not longer a duplicate then you need to explain why it is different – New Alexandria Feb 23 '18 at 03:48

1 Answers1

2

You already have an if test, so use that, setting your Boolean as you see fit. There are tons of ways of doing that, e.g.:

let success: Bool

if let range = someString.range(of: regexp, options: .regularExpression) {
    success = true
    let result = someString.substring(with: range)
    print(result)
} else {
    success = false
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044