首先,我是一个使用正则表达式的N00b,它就像一种新语言,我正在努力使用ATM并寻找方向。
我有一个具有序列号字段的表单,但字段内容可以是3种可能的规则之一。
规则1:长度始终为13位置1始终为C位置2-5为 数字位置6是alpha位置7-13是数字
规则2:长度为8或9位置1-2为alpha位置3-8为数字 位置9是alpha
规则3:长度为9位置1-9为数字
我的问题:这是在正则表达式中可实现的公式 - 以及子问题:我可以查看的指针或可以破译的表达式?
道歉,如果这太过于n00b'esque - RegEx我的头脑:)
答案 0 :(得分:2)
尝试使用:
/^(C\d{4}[a-zA-Z]\d{7}|[a-zA-Z]{2}\d{6}[a-zA-Z]?|\d{9})$/
我认为最后一个alpha在规则#2中是可选的
<强>解释强>
The regular expression:
(?-imsx:^(C\d{4}[a-zA-Z]\d{7}|[a-zA-Z]{2}\d{6}[a-zA-Z]?|\d{9})$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
C 'C'
----------------------------------------------------------------------
\d{4} digits (0-9) (4 times)
----------------------------------------------------------------------
[a-zA-Z] any character of: 'a' to 'z', 'A' to 'Z'
----------------------------------------------------------------------
\d{7} digits (0-9) (7 times)
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
[a-zA-Z]{2} any character of: 'a' to 'z', 'A' to 'Z'
(2 times)
----------------------------------------------------------------------
\d{6} digits (0-9) (6 times)
----------------------------------------------------------------------
[a-zA-Z]? any character of: 'a' to 'z', 'A' to 'Z'
(optional (matching the most amount
possible))
----------------------------------------------------------------------
| OR
----------------------------------------------------------------------
\d{9} digits (0-9) (9 times)
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------