0

I have this email validation regex

[a-zA-Z0-9\\\\+\\\\.\\\\_\\\\%\\\\-\\\\+']{1,256}[\\\\@]{1}[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,64}([\\\\.]{1}[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,25})+

but it won't allow for emails like asd-asd@gmail.com ... i.e. using "-". I can't figure out how to make it work. Any ideas ?

AndreiBogdan
  • 10,858
  • 13
  • 58
  • 106
  • Try this: `^[\\w+.'%-]{1,256}@[a-zA-Z0-9][a-zA-Z0-9-]{0,64}([.][a-zA-Z0-9][a-zA-Z0-9-]{0,25})+$` – anubhava Dec 10 '18 at 16:25
  • ``\\\\`` inside character class `[...]` represents single ``\`` literal, not escape sequence. So ``\\\\-\\\\`` is like `a-a` range, in other words it also represents only ``\`` character. Use ``\\`` instead of ``\\\\`` if you want to use it as escape sequence. – Pshemo Dec 10 '18 at 16:26

2 Answers2

1

You can just append - in the first square brackets.

[a-zA-Z0-9\\\\+\\\\.\\\\_\\\\%\\\\-\\\\+'-]
                                         ▲      

This will ensure that dashes are allowed as well.

Glains
  • 2,773
  • 3
  • 16
  • 30
  • Is there a "full" email validation regex out there? Initially I got an issue with apostrophes ' ... now with dashes ... :( sigh – AndreiBogdan Dec 10 '18 at 16:26
  • @AndreiBogdan Is [this](https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression) related? – Glains Dec 10 '18 at 16:28
0

You can add - to the part before the @.

The full regex then looks like this: [a-zA-Z0-9\\\\+\\\\.\\\\_\\\\%\\\\-\\\\+'\-]{1,256}[\\\\@]{1}[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,64}([\\\\.]{1}[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,25})+

David3103
  • 125
  • 10
  • `-` placed at the end of `]` doesn't need to be escaped since it doesn't create a range, so it is not considered as metacharacter. Also you would need two ``\`` before it in Java string literals. – Pshemo Dec 10 '18 at 16:45
  • @Pshemo Thank you for the comment. You're right; I edited my answer and removed the escape sequence now. – David3103 Dec 10 '18 at 17:05
  • I was referring to ``\`` in `'\-]`. You don't need it, but even if you did it would need to be written as `'\\-]` if it was meant to be as escape sequence for regex. – Pshemo Dec 10 '18 at 17:13