2014-01-12 22 views
0

我有以下邏輯Ruby的正則表達式代碼字符串

def insert_type(type_list, user_input) 
    case user_input 
    when user_input == 'library_1' 
    type_list.slice!('library_' + RegEx for any digit after library_ and stop right there + '__') 
    type_list << user_input << '__' 
    when user_input == 'class_A_2' 
    type_list.slice!('class_' + RegEx for any digit after class_ and stop right there + _A + '__') 
    type_list << user_input << '__' 
    end 
end 

我試着做以下

[l][i][b][r][a][r][y][_]\d{0,5} #digit from 0 to 99999 

它的工作,但應該有一個更傳統的方式在那裏,我可以開始用l和下劃線結尾,然後添加數字,因爲type_list可能是:

puts type_list 
=> "username_John__userid_58173__userpass_8adsh20__class_A_2__library_0__" 
+1

我真的不明白你想要做什麼。你不能只是'__'(雙下劃線)? – nhahtdh

+0

看起來像這是你正在尋找'\ w + \ d {0,5}' – thefourtheye

+0

哦,讓我試試看。 – user3163916

回答

1

你想要的是S:

\w+?(\d{1,5}) 

或者,如果你想有一個特定的單詞,然後:

library_(\d{1,5}) 

將非貪婪地捕捉單詞字符,然後將數值添加到第一個捕獲組。

解釋:

  • 任何文字字符,包括_,非貪心,直到找到一個數字
  • 任何數字,從1到5位數字(在此使用{0,5}實際上是0到5 d igits)
  • 用圓括號()包圍數字可以捕獲該值。
+0

謝謝,但如果我想要的詞是圖書館怎麼辦?由於type_list在字符串中包含其他單詞,而庫不一定是第一個單詞? – user3163916

+0

如果你特別想要圖書館,那麼只需使用'library_(\ d {1,5})' – brandonscript

+0

:O不知道你能做到這一點!謝謝你,先生! – user3163916