0

I am trying to write a basic regex to validate an email address. For this specific case I am trying to make sure the string inputted only includes letters, numbers, "." and "@". Or in other words I am making sure it doesnt include characters like £&¬! etc.

I tried getting the NOT version of this [[:alnum:].@]+ so that it would highlight a character not in that set but I couldnt get it to work. I also tried characters not in [\W.@]+ (the . is meant to be escaped but stackoverflow is removing the \ from this post) but the \W is still picking up the . and @ symbols.

Mufasatheking
  • 387
  • 2
  • 6
  • 16

2 Answers2

0

There are lots of examples of regex patterns for email addresses out there. Here is a very basic/naive one that allows only alphanumeric and periods (and a single @). This one does not care if the domain part is in a valid format (i.e. things like "abc@gmail......com" would pass):

^[A-Za-z0-9.]+@[A-Za-z0-9.]+$
coffee-converter
  • 967
  • 4
  • 13
0

You can ...

  • ... match for positives (your regex plus anchors to make sure it matches the complete test string)
    ( ^[[:alnum:].@]+$ )
  • ... match for negatives which means that at some point an illegal character occurs
    ( [^[:alnum:].@] )

... and check whether there has been a match. n the first case that means 'ok', in the second 'fail'.

Theer are regex dialects that do not support posix character classes, in this case replace [:alnum:] with 0-9a-zA-Z.

collapsar
  • 17,010
  • 4
  • 35
  • 61