需求:驗證字符串格式為「兩個字母 + 兩位年份 + 兩位月份」,月份必須 01-12。本文給出嚴格正則,並解析字符類、分組、邊界斷言的設計考量。
^[a-zA-Z]{2}\d{2}(0[1-9]|1[0-2])$
| 片段 | 含義 | 示例匹配 |
|---|---|---|
^ | 字符串開始斷言 | - |
[a-zA-Z]{2} | 兩個英文字母(含大小寫) | ru, CA, Ab |
\d{2} | 兩位數字(年份後兩位) | 15, 09, 99 |
(0[1-9]|1[0-2]) | 月份 01-12:01-09 或 10-12 | 01, 09, 10, 12 |
$ | 字符串結束斷言 | - |
^[a-z]{2}\d{2}(0[1-9]|1[0-2])$
// JS
const regex = /^[a-zA-Z]{2}\d{2}(0[1-9]|1[0-2])$/;
console.log(regex.test('ru1509')); // true
console.log(regex.test('ca1312')); // true
console.log(regex.test('ab9913')); // false (月份 13 非法)
// Java
Pattern p = Pattern.compile("^[a-zA-Z]{2}\\d{2}(0[1-9]|1[0-2])$");
Matcher m = p.matcher("ru1509");
System.out.println(m.matches()); // true
# Python
import re
pattern = re.compile(r'^[a-zA-Z]{2}\d{2}(0[1-9]|1[0-2])$')
print(pattern.match('ru1509')) # 匹配對象
^([a-zA-Z]{2})(\d{2})(0[1-9]|1[0-2])$
// 組1: 前綴字母, 組2: 年份, 組3: 月份
\d{4} 匹配年月,無法校驗月份合法性。[0-1][0-9] 匹配月份,會匹配 00、19 等非法值。m 標志或用 \A \z 替代 ^ $。Pattern/RegExp,避免循環中重複創建。嚴格校驗月份的關鍵:分支交替 (0[1-9]|1[0-2]) 精確覆蓋 01-12。這個模式可復用於身份證、日期、批次號等所有含月份字段的正則。