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 = "[email protected]"

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)
}
3
  • FYI - your regular expression will match [email protected]==== or any other email address with garbage at either end. Commented Feb 22, 2018 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. Commented Feb 22, 2018 at 19:11
  • If this is not longer a duplicate then you need to explain why it is different Commented Feb 23, 2018 at 3:48

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I made a stupid mistake. Thank you for your help, dear friend.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.