我想要一个长度为 X 或 Y 字符的正则表达式。例如,匹配长度为 8 或 11 个字符的字符串。我目前已经这样实现了:^([0-9]{8}|[0-9]{11})$
.
我也可以将其实现为:^[0-9]{8}([0-9]{3})?$
我的问题是:我可以在不复制 [0-9]
的情况下使用这个正则表达式吗?零件 (这比这个简单的 \d
示例更复杂)?
最佳答案
有一种方法:
^(?=[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
关于regex - 匹配特定长度 x 或 y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12784338/