1

I have written a regEx in java for:

  1. Expression should start with a letter.
  2. Followed by letter or number or period or @
  3. Ends with abc.com or xyz.com

Regex i tried:

^[A-Za-z][A-Za-z0-9@\.]*?[abcxyz]\.com$

I think there is some problem in the 3rd condition. Can somebody please correct me or provide me a better regEx. Thanks in advance.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Zeeshan
  • 11,851
  • 21
  • 73
  • 98
  • `[A-Za-z0-9@\.]*?` This part looks fishy. Are you trying to match an email address? – nhahtdh Oct 20 '14 at 07:12
  • Are you trying to validate an email adress? Don't. Look here for a regex which catches most of valid adresses: http://stackoverflow.com/a/719543/1436981 – stuXnet Oct 20 '14 at 07:38

4 Answers4

4

You don't need to escape the dot inside the character class and also put abc and xyz inside a capturing or non-capturing group with | (Logical OR operator) as seperator.

^[A-Za-z][A-Za-z0-9@.]*?(?:abc|xyz)\.com$

Java regex would be,

^[A-Za-z][A-Za-z0-9@.]*?(?:abc|xyz)\\.com$

[abcxyz] in your regex matches a single character from the given list. That is , it would match a or b or c or x or y or z

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
3
^[A-Za-z][A-Za-z0-9@.]*?(?:\babc\b|\bxyz\b)\\.com$

Try this.[abcxyz] will match just 1 character like a,b, etc.

vks
  • 67,027
  • 10
  • 91
  • 124
  • @TheLostMind just used OP's regex.Will correct it thanx. – vks Oct 20 '14 at 06:50
  • @anubhava guess you should not have deleted your answer...u missed some brownie points :P – vks Oct 20 '14 at 06:51
  • 1
    No I always delete my answer if I find it is duplicate of an already posted answer and upvote the existing answer. And almost everyday I crossover daily rep limit anyway so couple of upvotes won't matter much anyway :) – anubhava Oct 20 '14 at 06:54
  • @anubhava dats something to look forward to :) – vks Oct 20 '14 at 06:55
1

May be I'm wrong but I guess you want to match an email address, so it's better to put the @ outside the character class to be sure there is only one:

^[A-Za-z][A-Za-z0-9.]*@[A-Za-z0-9.]*(abc|xyz)\\.com$

But a regex that matches email address is much more complex, see this

Toto
  • 89,455
  • 62
  • 89
  • 125
0
^[A-Za-z][A-Za-z0-9@.]*?(abc|xyz)\\.com$
T I
  • 9,785
  • 4
  • 29
  • 51
Beri
  • 11,470
  • 4
  • 35
  • 57
  • Thanks for adding \, didn't see java tag, so I used simple regexp notation:) Big thanks:) – Beri Oct 20 '14 at 06:52