-1

I'm trying to create a Regex expression in Java for an email address and I'm stuck. When I use some of the online Regex testers it works fine but in Java it doesn't seem to want to work.

Here's my expression: [a-zA-Z!$.&\\d]{4,24}[@][a-zA-Z]{2,}[.edu|.com|.net]

It is supposed to be:

  • a 4-24 character username that can have digits, ".", "&", "$", and "!" in it
  • "@" character following
  • at least 2 characters for the domain but can include stuff like "school.alt"
  • and the ending can only be ".net", ".com", or ".edu".

Can't figure out what I'm doing wrong.

Even if I test it against a simple email like "test@school.edu" it doesn't match.

dwagner6
  • 67
  • 6
  • 1
    Possibly related [What is the difference between square brackets and parentheses in a regex?](https://stackoverflow.com/a/9801697/256196) – Bohemian Feb 15 '18 at 18:19
  • Start with parts of the regexp and go step by step until you found out what part of it does not work as expected – MrSmith42 Feb 15 '18 at 18:22
  • Email addresses [are pretty weird](http://girders.org/2013/01/dont-rfc-validate-email-addresses.html) though. Consider if you really want this. (also, you domain currently can't include "school.alt"). – M. Prokhorov Feb 15 '18 at 18:25

2 Answers2

3

You could change the end of your regex to a non capturing group using the | or:

(?:\.edu|\.com|\.net)

Or as @Bohemian commented you could write this simpeler as \.(?:edu|com|net)

Right now you are using a character class [.edu|.com|.net]

[a-zA-Z!$.&\d]{4,24}[@][a-zA-Z]{2,}(?:\.edu|\.com|\.net)

The fourth bird
  • 96,715
  • 14
  • 35
  • 52
  • correct (except it's called a character *class*, not a character *set*), or simpler: `\.(?:edu|com|net)` – Bohemian Feb 15 '18 at 18:11
  • @Bohemian Ah ok, thank you! Then I guess the [first line](https://www.regular-expressions.info/charclass.html) is not entirely correct: "With a "character class", also called "character set"," – The fourth bird Feb 15 '18 at 18:15
0

You have some errors in your regular expression.

  1. \\d will also validate the prrsian numbers, for example: پنج or شش. So you should use [0-9].
  2. The braces around of @ is not needed.
  3. Last expresion .edu|.com|.net must be in round brackets. (.edu|.com|.net). Because it is not a set of characters, it is a strict expressions. Also the dot can be put out of brackets. \.(edu|com|net).
    1. You should to add ^ and $ before and after regular expression for validate total string.

So you regular expression will be: ^[a-zA-Z!$.&0-9]{4,24}@[a-zA-Z]{2,}\.(edu|com|net)$

BullyBoo
  • 52
  • 4