2013-01-19 63 views
0

首先,我是一個N00b正則表達式,它就像一種新的語言,我正在用ATM掙扎着尋找某個方向。複雜的正則表達式 - 是否有可能

我有一個具有序列號字段的表單,但字段內容可以是3種可能的規則之一。

的Rule1:長度總是13位置1常表示爲C 2-5的位置是 數字6位是α位7-13是數字

規則2:長度是8或9的位置圖1-2是α位3-8是數字 當前位置9是α-

規則3:長度爲9的位置1-9是數字

我的問題:這是可以在正則表達式中實現的公式 - 子問題:指向我可以看的地方或可以解釋的表達式的指針?

道歉,如果這太n00b'esque - 正則表達式做我的頭:)

+1

持續8或9,則瓦特如果長度是8,會發生帽子嗎?是最後位置字母表嗎?或者會有更少的數量? – nhahtdh

+0

我確信這是基本的,我剛剛開始如此看待(和弄糊塗)手冊和示例,感謝您的輸入。 – stuartmcd69

回答

2

有一試:

/^(C\d{4}[a-zA-Z]\d{7}|[a-zA-Z]{2}\d{6}[a-zA-Z]?|\d{9})$/ 

我想,最後的字母是在規則#可選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 
---------------------------------------------------------------------- 
+0

WOW,非常感謝這個,細節真棒,正是我想要學習的東西。這裏遲到了,但會讓你知道它是如何擺脫的。 – stuartmcd69

+0

「|」性格/規則/任何給我的「燈泡」時刻。謝謝。 – stuartmcd69