Here is something to help you
The regex
^(?:([\w-]+)@)?([\w-\.]+\.[a-zA-Z][\w-]+)(?::([0-9]{1,5}))?$
Should do what you want. Let's explain :
You first want to match (if it exist) a user followed by @
. To match a word you can use \w
but in your regex you specified that you wanted the char -
wich isn't include in \w
(but _
is). So to match your user you will do :
(?:([\w-]*)@)?
Then you want to match a domain name
([\w-\.]+\.[a-zA-Z][\w-]+)
The domain name have to finish by at least one dot followed by a word (the top level domain). The top level domain doesn't begin by a digit (this rule was created based on the usedTopLevelDomainList
And to finish you want to match a port wich is a 1-5 digit :
(?::([0-9]{0,5}))?
As pointed out the regex can match IPv4 that aren't within the 255 max range.
The regex to verify an IPv4 is :
^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
Source. I've updated the previous regex to exclude the IP match from my regex and add a OR
statement for the domain name to match either an IPv4 based on the above regex or a domain as I've defined it previously.
Result with group to separate each part :
^(?:([\w-]+)@)?((?:[\w-\.]+\.[a-zA-Z][\w-]+)|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?::([0-9]{1,5}))?$
Result without any group to just match valid case :
^(?:[\w-]+@)?(?:(?:[\w-\.]+\.[a-zA-Z][\w-]+)|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?::[0-9]{1,5})?$