2011-12-13 229 views
0

,我有以下字符串集:正確的正則表達式匹配

some_param[name] 
some_param_0[name] 

我希望捕獲some_param,,從他們。 我的正則表達式知識很薄弱。我嘗試了以下方法,但對兩種情況都不起作用。

/^(\D+)_?(\d{0,2})\[?(.*?)\]?$/.exec("some_param_0[name]") //works except for the trailing underscore on "some_param" 

什麼是正確的正則表達式?

回答

3
/^(\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"] 
+0

我想他想刪除尾部下劃線..我說得對嗎?我用`/ ^([a-zA-Z _] +)(?:_(\ d {0,2}))?(?:\ [([^ \ [\]] *)\]) $ /`但它看起來不起作用(至少在Python中) – redShadow 2011-12-13 23:49:06

+0

@redShadow,OP中的RegExp將它從捕獲組1中除去,所以我假定海報想要它。 – 2011-12-13 23:52:00

0

請,檢查follwing正則表達式 「(\ W +)_(\ d)[(\ W +)]」 喲可以測試@http://rubular.com/

1

得到它! (邁克的回答服用):

/^(\D+)(?:_(\d+))?(?:\[([^\]]*)\])/ 

'some_param[name]' => ('some_param', None, 'name') 
'some_param_0[name]' => ('some_param', '0', 'name') 

(至少在Python它的工作原理)

更新:一點點額外的,我寫它擺弄,通過使用命名組使結果更清潔:

^(?P<param>\D+)(?:_(?P<id>\d+))?(?:\[(?P<key>[^\]]*)\]) 

UPDATE: