.net 用于验证十六进制字符串的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/287684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:36:37  来源:igfitidea点击:

Regular expression to validate hex string

.netregex

提问by Alonso

I'm using this simple regular expression to validate a hex string:

我正在使用这个简单的正则表达式来验证十六进制字符串:

^[A-Fa-f0-9]{16}$

As you can see, I'm using a quantifier to validate that the string is 16 characters long. I was wondering if I can use another quantifier in the same regex to validate the string length to be either 16 or 18 (not 17).

如您所见,我使用量词来验证字符串的长度是否为 16 个字符。我想知道是否可以在同一个正则表达式中使用另一个量词来验证字符串长度是 16 还是 18(不是 17)。

回答by David Norman

I believe

我相信

^([A-Fa-f0-9]{2}){8,9}$

will work.

将工作。

This is nice because it generalizes to any even-length string.

这很好,因为它可以推广到任何偶数长度的字符串。

回答by Jon Skeet

That's just a 16 character requirement with an optional 2 character afterwards:

这只是一个 16 个字符的要求,之后还有一个可选的 2 个字符:

^[A-Fa-f0-9]{16}([A-Fa-f0-9]{2})?$

The parentheses may not be required - I'm not enough of a regex guru to know offhand, I'm afraid. If anyone wants to edit it, do feel free...

括号可能不是必需的 - 恐怕我不是一个正则表达式大师,无法立即知道。如果有人想编辑它,请随意...

回答by VonC

^(?:[A-Fa-f0-9]{16}|[A-Fa-f0-9]{18})$

回答by John Fiala

I'd probably go with

我可能会去

/^[a-f0-9]{16}([a-f0-9]{2})?$/i

myself. I think it's more readable to set the regex as case insensitive and only list the character range once. That said, just about all of these answers work.

我。我认为将正则表达式设置为不区分大小写并且只列出一次字符范围更具可读性。也就是说,几乎所有这些答案都有效。