You can specify alternation with the |
character, so a|b
means "match either a
or b
". In this case it would look something like this:
^$|^[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}:[0-9a-fA-F]{1,4}$
The regex ^$
will match empty strings, so ^$|<current-regex>
means "match either an empty string, or whatever <current-regex>
matches (in this case IPv6)". You could use ^\s*$
in place of ^$
if you want strings that only consist of whitespace character to also be considered "empty".
This just handles the first part of the question, handling the compression like FE80::1
is more complex and it looks like there are already some other good answers for that in comments (note that I don't think this question is a dupe, because the "also matching an empty string" part isn't present in those questions).
edit: If it is part of a larger regex, then you should wrap everything in a group and get rid of the ^$
, so it would be something like (|<current-regex>)
. Since there is nothing before the |
, it means that the group can match either empty strings or whatever your current regex would match.