2

I need a regular expression to accept only two below formats:

string.string
[email protected]

I have used a pattern but it only accepts this format: [email protected]

How to update this pattern

/^[ ]*[a-zA-Z0-9!#$%&\'*+\\/=?^_`’{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`’{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?[ ]*$/g

to accept both of the formats.

Mariano
  • 6,423
  • 4
  • 31
  • 47
Owais
  • 49
  • 12
  • 1
    What is your regex flavour? – Stephan Nov 19 '15 at 09:47
  • If you're validating e-mails, you might be interested in http://www.regular-expressions.info/email.html and [Using a regular expression to validate an email address](http://stackoverflow.com/q/201323/5290909) – Mariano Nov 19 '15 at 10:05
  • Thanks. This is very much described. i will look into it. however, i have created a regular expression so far so good for the requirement as i am running out of time. `(^[ ]*[a-zA-Z0-9!#$%&\'*+\\/=?^_`’{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`’{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?[ ]*$)|([a-zA-Z0-9]+\.[a-zA-Z0-9]+)` – Owais Nov 19 '15 at 10:07
  • It looks like you're reinventing the wheel, with an expresssion that would probably fail (of course, that depends on your scope). – Mariano Nov 19 '15 at 10:19

3 Answers3

1

Actually, I have updated the pattern which accepts both the formats, now.

Below is the pattern to accept both the format. i.e. abc.def and [email protected]

/(^[ ]*[a-zA-Z0-9!#$%&\'*+\\/=?^_`’{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`’{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?[ ]*$)|([a-zA-Z0-9]+\.[a-zA-Z0-9]+)/
Owais
  • 49
  • 12
0

You can go with this way simpler version:

^\w+[.]\w+$|^\w+@\w+[.]com$

Correction thanks to Mariano

Community
  • 1
  • 1
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
0

Try this:

^\s*\w+(?:\.\w+|@\w+\.com)\s*$

Description

Regular expression visualization

You can replace \w+ with a character class ([\w.|]+ for example) to add other accepted characters.

Stephan
  • 41,764
  • 65
  • 238
  • 329