2012-08-09 65 views
3

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

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

我该如何解决问题?

+0

首先应该是'^ [A-Fa-f0-9] + $'吗? – 2012-08-09 06:06:39

回答

9

您很可能需要一个+,所以regex = '^[a-fA-F0-9]+$'。但是,我会小心(可能)在字符串的开始处考虑诸如可选的0x之类的东西,这会使其成为^(0x|0X)?[a-fA-F0-9]+$'

+2

'^(0x | 0X)*'应该是'(0 [xX])?',否则它也会与不是标准十六进制字符串的“0x0x0x0x1234abcd”匹配。看到我的回答 – 2012-08-09 06:20:00

+0

@PreetKukreti确实,很好。我会更新我的答案。 – Yuushi 2012-08-09 06:31:41

6

^[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> 
1

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

相关问题