-3

I'm trying today to build a regex to make it match to email adress.

I've made one but not working in all the cases I want.

I would a Regex to match with all email address finishing with 2 characters after the dot or only the .com.

I hope to be clear enought,

  • aaaaaa@bbbb.uk --> should work
  • aaaaaa@bbbb.com --> should work
  • aaaaaa@bbbb.cc --> should work

  • aaaaaa@bbbb.ukk --> should not work

  • aaaaaa@bbbb. --> should not work

this is my code:

#include <stdio.h>
#include <stdlib.h>
#include <regex.h>

int main (void)
{
  int match;
  int err;
  regex_t preg;
  regmatch_t pmatch[5];
  size_t nmatch = 5;
  const char *str_request = "1aaaak@aaaa.ukk";

  const char *str_regex = "[a-zA-Z0-9][a-zA-Z0-9_.]+@[a-zA-Z0-9_]+.[a-zA-Z0-9_.]+[a-zA-Z0-9]{2}";          

  err = regcomp(&preg, str_regex, REG_EXTENDED);
  if (err == 0)
    {
      match = regexec(&preg, str_request, nmatch, pmatch, 0);
      nmatch = preg.re_nsub;
      regfree(&preg);
      if (match == 0)
    {
          printf ("match\n");
          int start = pmatch[0].rm_so;
          int end  = pmatch[0].rm_eo;
          printf("%d - %d\n", start, end);
    }
      else if (match == REG_NOMATCH)
    {
          printf("unmatch\n");
    }
}
  puts ("\nPress any key\n");
  getchar ();
  return (EXIT_SUCCESS);
 }
joelmoluni
  • 15
  • 3

1 Answers1

0
"[a-zA-Z0-9][a-zA-Z0-9_.]+@[a-zA-Z0-9_]+\\.(com|[a-zA-Z]{2})$"

https://regex101.com/ is a very good tool for that

\. means a litteral dot ;

(|) means an alternative ;

$ means the end of the line, as we do not want some trailing chars after the match.

Boiethios
  • 38,438
  • 19
  • 134
  • 183