2016-06-01 54 views
0

我正在擴展rouge shell詞法分析器爲我的jekyll網站,我想要做以下事情。匹配一個字符串,但只捕獲它的紅寶石匹配的子串

  1. 匹配--word。捕獲word,丟棄--
  2. 比賽<word>。捕獲word,丟棄<>
  3. 匹配word=anyNumber.word。捕獲wordanyNumber.word,丟棄=

首先,我已經試過/(?=-+)\w/,沒有匹配,然後我試圖做反向並丟棄word/-+(?=\w*)/,和它的工作。我做錯了什麼?

+1

添加一個小例子和期望的結果將是有益的。如果你這樣做,一定要爲每個輸入值('str =「...」')分配一個變量,以便讀者可以引用變量而不必定義它們。 –

回答

2

我懷疑你是否過度這個。這裏不需要向前看或向後看。

str = "foo --word1 <word2> word3=anyNumber.word4" 

p /--(\w+)/.match(str).captures 
# => ["word1"] 

p /<([^>]+)>/.match(str).captures 
# => ["word2"] 

p /(\w+)=([\w.]+)/.match(str).captures 
# => ["word3", "anyNumber.word4"] 
0
str = "--hopscotch <dodgeball> cat=9.lives" 

str[/(?<=\-\-)\w+/] 
    #=> "hopscotch" 
str[/(?<=\<)\w+(?=\>)/] 
    #=> "dodgeball" 
str.scan /(?:\w+(?=\=))|(?<=\=)\d+\.\w+/ 
    #=> ["cat", "9.lives"]