正则表达式IPv6验证和可选方括号? [英] Regex IPv6 validation and optional square brackets?

查看:162
本文介绍了正则表达式IPv6验证和可选方括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,所有正则表达式新手都在这里.

Hi all regex newbie here.,

我正在尝试编写一个用于验证IPv6地址的正则表达式.我尚未添加端口部分,我想首先使地址部分开始工作.

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?

推荐答案

Regex是用于字符串模式匹配的好工具,但是您在这里碰到了它的弱点之一.匹配成对的括号可能会比较棘手.

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.

但是,在您的情况下,问题并不太复杂,并且出现了一个非常简单的解决方案:只需将整个表达式与所需的两个方括号匹配,或者将整个表达式与两个方括号都匹配即可.换句话说,将表达式的主要部分重复两次,一次用方括号,一次不用方括号,并在它们之间用or的管道表示:

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]+)\

希望有帮助.

这篇关于正则表达式IPv6验证和可选方括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆