Dart/Flutter – How to extract emails from a String

In this post, I will share you an example of how to extract ALL emails in a String.

Assume we have a string like below, we need to extract abc@mail.com and test—100@mail.com from this string.

'This is an email: abc@mail.com. '
'This is another email: test---100@mail.com. '
'But this is not an email: https://coflutter.com.'

List<String> extractEmailsFromString(String string) {
  final emailPattern = RegExp(r'\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b',
      caseSensitive: false, multiLine: true);
  final matches = emailPattern.allMatches(string);
  final List<String> emails = [];
  if (matches != null) {
    for (final Match match in matches) {
      emails.add(string.substring(match.start, match.end));
    }
  }

  return emails;
}

void main() {
  final emails = extractEmailsFromString(
      'This is an email: abc@mail.com. '
      'This is another email: test---100@mail.com. '
      'But this is not an email: https://coflutter.com.');
  print(emails);
}

// Output
[abc@mail.com, test---100@mail.com]

If you are looking for mobile/web Software Engineers to build you next projects, please Contact Nextfunc team here!

Tagged : / / / /
5 3 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
vupn
vupn
19 days ago
very helpful, thanks admin
1
0
Would love your thoughts, please comment.x
()
x