我需要创建正则表达式来验证用户是否输入:
- 4 位数 或
- 值类似于 XXXXXX-YY,其中 X 是从 I 到 XXXIII 的罗马数字,YY 是两个拉丁字符 (A-Z)
最佳答案
根据要求,这些是可能的罗马数字格式。为了便于阅读,仅显示 X 的最大数量。
XXX III (or: <empty>, I or II instead of III) XX V (or: IV, IX and X instead of IV)
我建议使用这种紧凑的模式:
/^(\d{4}|(?=[IVX])(X{0,3}I{0,3}|X{0,2}VI{0,3}|X{0,2}I?[VX])-[A-Z]{2})$/i
解释:
^ Begin of string
( Begin of group 1.
\d{4} 4 digits
| OR
(?=[IVX]) Look-ahead: Must be followed by a I, V or X
( Begin of group 2.
X{0,3}I{0,3} = 0 1 2 3 + { 0 ; 10 ; 20 ; 30} (roman)
| OR
X{0,2}VI{0,3} = 5 6 7 8 + { 0 ; 10 ; 20 } (roman)
| OR
X{0,2}I?[VX] = 4 9 + { 0 ; 10 ; 20 } (roman)
) End of group 2
-[A-Z]{2} Postfixed by a hyphen and two letters
) End of group 1.
$ End of string
关于javascript - 如何创建正则表达式检查罗马数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9340823/