匹配特定长度x或y

Lao*_*jin 28 regex

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

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

我的问题是:我可以使用这个正则表达式而不重复该[0-9]部分(这比这个简单的\d例子更复杂)?

Tim*_*ker 47

有一种方法:

^(?=[0-9]*$)(?:.{8}|.{11})$
Run Code Online (Sandbox Code Playgroud)

或者,如果你想先做长度检查,

^(?=(?:.{8}|.{11})$)[0-9]*$
Run Code Online (Sandbox Code Playgroud)

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

说明:

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