/^(\w+?)_?(\d{0,2})(?:\[([^\[\]]*)\])?$/
(\w+?)
使用non-greedy quantifier捕獲標識符部分沒有任何尾隨_
。
_?
是貪婪的,所以會擊敗上一部分的+?
。
(\d{0,2})
將捕獲0-2位。它是貪婪的,所以即使標識符和數字之間沒有_
,也會捕獲數字。
(?:...)?
使方括號部分可選。
\[([^\[\]]*)\]
捕獲方括號內部分的內容本身不包含方括號。
'some_param_0[name]'.match(/^(\w+?)_(\d{0,2})(?:\[([^\[\]]*)\])?$/)
產生像的數組:
["some_param_0[name]", // The matched content in group 0.
"some_param", // The portion before the digits in group 1.
"0", // The digits in group 2.
"name"] // The contents of the [...] in group 3.
注意,非貪婪量詞可能與\d{0,2}
有界重複奇怪交互。
'x1234[y]'.match(/^(\w+?)_?(\d{0,2})(?:\[([^\[\]]*)\])?$/)
產生
["x1234[y]","x12","34","y"]
我想他想刪除尾部下劃線..我說得對嗎?我用`/ ^([a-zA-Z _] +)(?:_(\ d {0,2}))?(?:\ [([^ \ [\]] *)\]) $ /`但它看起來不起作用(至少在Python中) – redShadow 2011-12-13 23:49:06
@redShadow,OP中的RegExp將它從捕獲組1中除去,所以我假定海報想要它。 – 2011-12-13 23:52:00