Quantcast
Channel: User LuckyLuke - Stack Overflow
Viewing all articles
Browse latest Browse all 37

Answer by LuckyLuke for Using a regular expression to validate email addresses

$
0
0

What you have written works with some small modifications if that is what you want to use, however you miss a '+' at the end.

1)

 ^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$ 

The caret and dollar character match positions rather than characters, ^ is equal to the beginning of line and $ is equal to the end of line, they are used to anchor your regex. If you write your regex without those two you will match email addresses everywhere in your text, not only the email addresses which is on a single line in this case. If you had written only the ^ (caret) you would have found every email address which is on the start of the line and if you had written only the $ (dollar) you would have found only the email addresses on the end of the line.

Blah blah blah someEmail@email.comblah blah

would not give you a match because you do NOT have a email address at the beginning of line and the line does not terminate with it either so in order to match it in this context you would have to drop ^ and $.

  1. Grouping is used for two reasons as far I know: Back referencing and... grouping. Grouping is used for the same reasons as in math, 1 + 3 * 4 is not the same as (1 + 3) * 4. You use parentheses to constrain quantifiers such as '+', '*' and '?' as well as alternation '|' etc.

You also parentheses for back referencing, but since I can't explain it better I would link you to: http://www.regular-expressions.info/brackets.html

I will encourage you to take a look at this book, even though you only read the first 2-3 chapters you will learn a lot and it is a great book! http://oreilly.com/catalog/9781565922570


And as the commentators say, this regex is not perfect but it works and show you what you had forgotten. You were not far away!


UPDATED as requested:

The '+', '*' and '?' are quantifiers. And is also a good example where you group.

  • '+' mean match whatever charachter preceeds it or group 1 or n times.
  • '*' mean match whatever charachter preceeds it 0 or n times.
  • '?' mean match whatever charachter preceeds it or the group 0 or 1 time.

n times meaning (indefinitely)

The reason why you use [a-zA-Z0-9]+ is without the '+' it will only match one character. With the + it will match many but it must match at least one. With * it match many but also 0, and ? will match 1 character at most but also 0.


Viewing all articles
Browse latest Browse all 37

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>