使用正则表达式验证十六进制字符串

时间:2012-08-09 06:01:25

标签: regex

我正在使用正则表达式验证字符串是否为十六进制。

我使用的表达式是^[A-Fa-f0-9]$。当我使用它时,字符串AABB10被识别为有效的十六进制,但字符串10AABB被识别为无效。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:18)

您最有可能需要+,所以regex = '^[a-fA-F0-9]+$'。但是,我会小心(或许)在字符串的开头考虑可选的0x这样的事情,这将使它成为^(0x|0X)?[a-fA-F0-9]+$'

答案 1 :(得分:7)

^[A-Fa-f0-9]+$

应该有效,+匹配1或更多字符。

使用Python:

In [1]: import re

In [2]: re.match?
Type:       function
Base Class: <type 'function'>
String Form:<function match at 0x01D9DCF0>
Namespace:  Interactive
File:       python27\lib\re.py
Definition: re.match(pattern, string, flags=0)
Docstring:
Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found.

In [3]: re.match(r"^[A-Fa-f0-9]+$", "AABB10")
Out[3]: <_sre.SRE_Match at 0x3734c98>

In [4]: re.match(r"^[A-Fa-f0-9]+$", "10AABB")
Out[4]: <_sre.SRE_Match at 0x3734d08>

理想情况下,您可能需要^(0[xX])?[A-Fa-f0-9]+$之类的内容,以便与0x

等常见0x1A2B3C4D格式的字符串进行匹配
In [5]: re.match(r"^(0[xX])?[A-Fa-f0-9]+$", "0x1A2B3C4D")
Out[5]: <_sre.SRE_Match at 0x373c2e0>

答案 2 :(得分:1)

你忘了'+'吗?尝试“^ [A-Fa-f0-9] + $”

相关问题