2

I want to extract email ids from string. I have Regex pattern for email

const val EMAIL_REGEX = "^[A-Za-z](.*)([@])(.+)(\\.)(.{1,})"

i tried this but its not extracting emails.

const val EMAIL_REGEX = "^[A-Za-z](.*)([@])(.+)(\\.)(.{1,})"
val emailMatcher = EMAIL_REGEX.toRegex()
val tmpList = emailMatcher.findAll(html).map { it.value }.toList()

but I am getting same string as it is.

I want the same result which we can get from this Python code.

re.findall(r"[a-z0-9.\-+_]+@[a-z0-9.\-+_]+\.[a-z]+", response.text, re.I)
Learn Pain Less
  • 2,274
  • 1
  • 17
  • 24
  • Please note that it takes a much more complex regex to match email addresses exactly: see [this question](https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression). – gidds Jul 08 '20 at 16:09

1 Answers1

3

You can use below method:

fun getEmailAddressesInString(text: String): ArrayList<String>? {
        val emails: ArrayList<String> = ArrayList()
        val matcher =
            Pattern.compile("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}")
                .matcher(text)
        while (matcher.find()) {
            emails.add(matcher.group())
        }
        return emails
    }
Shalu T D
  • 3,921
  • 2
  • 26
  • 37