1

I want an existing email regex to fail when entering a period (".") before the @.

This is the regex I have right now:

^[a-zA-Z]+[a-zA-Z0-9.]+@domain.com$

These should pass:

test.a@domain.com
a.test@domain.com

But these shouldn't:

.test@domain.com
test.@domain.com

The first case starting with period is handled but second case is not.

Tomarto
  • 2,755
  • 6
  • 27
  • 37
  • @dan08 not if it's square brackets - then it loses its special meaning. – VLAZ Nov 29 '16 at 22:48
  • For real! Did not know that. comment rescinded. – Dan Nov 29 '16 at 22:49
  • @dan08 yeah - most characters lose theirs special meaning in square brackets. The ones that most notably don't are `[]` (you still need to escape those), as well as `-` which indicates a character range. However, if placed in the beginning or the end, then it's treated as a dash. – VLAZ Nov 29 '16 at 22:52

3 Answers3

1

This should work without requiring two or more characters before the @ sign.

^[a-zA-Z][a-zA-Z0-9]*(?:\.+[a-zA-Z0-9]+)*@domain\.com$

Here's how it breaks down:

^                  Make sure we start at the beginning of the string
[a-zA-Z]           First character needs to be a letter
[a-zA-Z0-9]*       ...possibly followed by any number of letters or numbers.
(?:                Start a non-capturing group
    \.+            Match any periods...
    [a-zA-Z0-9]+   ...followed by at least one letter or number
)*                 The whole group can appear zero or more times, to
                     offset the + quantifiers inside. Otherwise the
                     period would be required
@domain\.com$      Match the rest of the string. At this point, the
                     only periods we've allowed are followed by at
                     least one number or letter
Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129
0

I would try: ^[a-zA-Z]+[a-zA-Z0-9.]*[a-zA-Z0-9]+@domain.com$

  • Note that this requires at least two characters before the @, so `a@domain.com`, for example, would fail. That might or might not be what you want. – Matthew Crumley Nov 29 '16 at 23:07
  • True - I was trying to keep this close to his original regex because it seemed that he wanted it to start with a letter. – theTrueMikeBrown Nov 29 '16 at 23:55
  • Oops, I didn't notice that it couldn't start with a number either. Anyway, that wasn't really a criticism, just a note about the exact meaning/implication of the expression. – Matthew Crumley Nov 30 '16 at 00:46
0

Try this regex: ^[\w.+-]*[^\W.]@domain\.com$.

  • [\w.+-]* matches any number of alphanumerical characters, +, - and .
  • [^\W.] matches any character that is not a non-alphanumerical character or a . (which means any accepted character but .)
  • @domain\.com matches the rest of the email, change the domain as you wish or use @\w\.\w+ for matching most domains. (matching all domains is more complex, see more complete examples of email matching regex here)
Community
  • 1
  • 1
Nicolas
  • 6,611
  • 3
  • 29
  • 73