0

I'm trying to create a regex that doesn't allow digits or spaces in the beginning. I've tried doing something like this:

^[\S][\D][\w+_.-]+@{1}[\w_.-]+\.{1}[a-zA-z]*$

However, when I use 4test@example.com it says it's an email, but when I use 4test@example.com it says it's not an email. In both cases, I'd like for it to say it's not an email. There shouldn't be a space or digit, how can I combine these two: [\S][\D] so that it works correctly?

user2896120
  • 3,180
  • 4
  • 40
  • 100
  • Hint: Use a negated character class `^[^\d\s][\w_.-]+` ... – Tim Biegeleisen Feb 05 '20 at 06:22
  • Please, have a look at these sites: [TLD list](https://www.iana.org/domains/root/db); [valid/invalid addresses](https://en.wikipedia.org/wiki/Email_address#Examples); [regex for RFC822 email address](http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) – Toto Feb 05 '20 at 09:45

1 Answers1

0

In your pattter \S will match any non whitespace char and it will also match a digit.

As mentioned in the comment, you can exclude matching the digit using a negated character class. If If you repeat the character class after that 1+ times the part before the @ should contain at least 2 characters.

If the minumum should be 1 char, you could use a * instead of a +.

Note that you don't need {1} and that [a-zA-z] can match more than [a-zA-Z]

If you repeat the character class [a-zA-Z]* at the end 0+ times using * the match could possibly also match a dot only.

You could update the pattern to:

^[^\d\s][\w_.-]*@[\w_.-]+\.[a-zA-Z]+$

Regex demo


If using \S is too broad, another option could be using a negative lookahead asserting not a digit followed by repeating the character class 1+ times:

^(?!\d)[\w_.-]+@[\w_.-]+\.[a-zA-Z]+$

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70