41

我想要一个长度为 X 或 Y 个字符的正则表达式。例如,匹配长度为 8 或 11 个字符的字符串。我目前已经这样实现了:^([0-9]{8}|[0-9]{11})$

我也可以将其实现为:^[0-9]{8}([0-9]{3})?$

我的问题是:我可以在不复制[0-9]部分的情况下拥有这个正则表达式(这比这个简单的\d例子更复杂)吗?

4

3 回答 3

64

有一种方法:

^(?=[0-9]*$)(?:.{8}|.{11})$

或者,如果您想先进行长度检查,

^(?=(?:.{8}|.{11})$)[0-9]*$

这样,您只有一次复杂的部分和.长度检查的通用部分。

解释:

^       # Start of string
(?=     # Assert that the following regex can be matched here:
 [0-9]* # any number of digits (and nothing but digits)
 $      # until end of string
)       # (End of lookahead)
(?:     # Match either
 .{8}   # 8 characters
|       # or
 .{11}  # 11 characters
)       # (End of alternation)
$       # End of string
于 2012-10-08T15:10:44.613 回答
2

使用 Perl,您可以:

my $re = qr/here_is_your_regex_part/;
my $full_regex = qr/$re{8}(?:$re{3})?$/
于 2012-10-08T15:10:42.413 回答
2

对于我们这些想要捕捉相同倍数的不同长度的人来说,试试这个。

^(?:[0-9]{32})+$

32您要为 (32, 64, 96, ...) 捕获所有长度的倍数在哪里。

于 2018-02-06T10:37:56.227 回答