regex - 匹配特定长度 x 或 y

标签 regex

我想要一个长度为 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/

相关文章:

regex - 多行 sublime text 语言模块定义

Python re.split 和 re.findall : grouping and capturing

Java 库验证 URL 并从字符串中删除 URL 参数

java - 用于检查 "Must contain English Alphabets & Can contain either Digit/Dot/Hyphen/Space"的 Java 正则表达式是什么?

java拆分正则表达式: split string using any text between curly brackets and keep the delimiter

regex - CMake 中的版本正则表达式

mysql - REGEXP_REPLACE 无法按预期替换逗号中的字符wrapt

c# - 正在解析 '\L' - 无法识别的转义序列

xml - 如何使用linux csplit 分割海量XML文件?

php - 用于分解配方列表元素的正则表达式语法