title: regex dice roll
body: <p>This is an example question from codefights.com 
  The object is to calculate the maximum score for a dice roll. To solve this problem, I have created a regex. It fails for one case (and passes all others):  </p>
  
  <p><code>pat = /(?&lt;rolls&gt;\d{1,2})?d(?&lt;sides&gt;\d{1,2})(?&lt;sign&gt;\+|\-)?(&lt;mod&gt;\d{1,2}|L)?/</code></p>
  
  <p>rules: "4d6-L1d20-10 did4n't expect that"
  Output:
  47
  Expected Output:
  38</p>
  
  <p>The only way I can sum that input to 38 is if I consider (4x6) - 6(L in this context <a href="https://en.wikipedia.org/wiki/Dice_notation" rel="nofollow">https://en.wikipedia.org/wiki/Dice_notation</a>) Then (ignoring there is no white space) + (1x20). I cannot think of a reason why the total is not 28 instead of 38. (1x20) - 10 is a legit formula according to the rules. I would really appreciate some insight into this problem or an idea on what logic I can use to solve it. </p>
  
  <pre><code>def bugsAndBugfixes(rules)
    matches = []
    pat = /(?&lt;rolls&gt;\d{1,2})?d(?&lt;sides&gt;\d{1,2})(?&lt;sign&gt;\+|\-)?(?&lt;mod&gt;\d{1,2}|L)?/
    rules.scan(pat) { matches &lt;&lt; $~ }
    result = 0
    matches.each do |match|
      c= Hash[ match.names.zip( match.captures ) ]
      c['rolls'] = 1 unless c['rolls']
      if c['sign'] == '-'
        result+=(c['rolls'].to_i * c['sides'].to_i) - c['mod'].to_i
      else
        result+=(c['rolls'].to_i * c['sides'].to_i) + c['mod'].to_i
      end
    end
  result
  end
  </code></pre>
  
  <p>end</p>
  
  <hr>
  
  <p>For rules = "Roll d6-3 and 4d4+3 to pick a weapon, and finish the boss with 3d7!",
  the output should be
  bugsAndBugfixes(rules) = 43.</p>
  
  <p>There are three formulas in the rules.</p>
  
  <p>d6-3 indicates a single roll of a 6-sided die, with 3 subtracted from the result. The maximum number that is possible to get is thus 6 - 3 = 3.
  4d4+3 stands for 4 rolls of a 4-sided die, with 3 added to the result. It is possible to get 4 * 4 + 3 = 19 points.
  3d7 means 3 rolls of a 7-sided die. The maximum number to obtain with it is 3 * 7 = 21.</p>