问题
Hi all regex newbie here.,
I am trying to write a regex that validates IPv6 addresses. I haven't added the port part yet, I want to get the address portion working first.
This is what I have so far:
\\[?(?:[:0-9A-Fa-f]+)\\]?
This makes the opening and closing brackets optional. But as you can see they are independently optional. Is there a way with regexes to require either both opening and closing brackets, or neither?
回答1:
Regex is a great tool for string pattern matching, but you've hit upon one of its weakness here. Matching pairs of brackets can get tricky.
In more complex situations -- ie when trying to read program code -- the solution is not to use regex at all, but to use a proper code parser.
Even fairly simple cases can be tricky to answer because the regex syntax involved can be quite hairy, and also because with more advanced regex features like this, different implementations may use different syntax. This question might provide some hints as to how to go about it, and the different syntaxes you might use.
However in your case, the problem isn't too complex, and a fairly simple solution presents itself: simply match the whole expression with both brackets required or the whole expression with neither bracket. In other words, repeat the main part of your expression twice, once with brackets and once without, and a pipe for or
between them:
\(\[(?:[:0-9A-Fa-f]+)\])|(?:[:0-9A-Fa-f]+)\
Hope that helps.
回答2:
I see it is an old question... but you can also use in this regex: ^([0-9a-fA-F]+:){7}[0-9a-fA-F]+$ or this one: ^[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}$
来源:https://stackoverflow.com/questions/10180798/regex-ipv6-validation-and-optional-square-brackets