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

use*_*216 12 regex

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

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

我该如何解决这个问题?

Yuu*_*shi 23

你很可能需要一个+,所以regex = '^[a-fA-F0-9]+$'.但是,我会小心(也许)0x在字符串的开头想一些可选的东西,这样就可以了^(0x|0X)?[a-fA-F0-9]+$'.

  • `^(0x | 0X)*`应该是`(0 [xX])?`否则它也匹配"0x0x0x0x1234abcd",它不是标准的十六进制字符串.看我的ans (4认同)
  • 也许最好确保您的十六进制字符串格式化为适合您上下文的十六进制字符串,例如具有 6 位数字的 css 颜色,并断言多个字符而不是无限数量的字符。例如 `^(0[xX]){1}[A-Fa-f0-9]{6}$ | ^#[A-Fa-f0-9]{6}$` (2认同)

Pre*_*eti 8

^[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>
Run Code Online (Sandbox Code Playgroud)

理想情况下,你可能想要这样的东西^(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>
Run Code Online (Sandbox Code Playgroud)