Search code examples
coffeescripthubot

Hubot matching on multiple tokens per line?


How can I match on multiple occurrences of a token in a single message.

module.exports = (robot) ->
  robot.hear /ITEM=(\d+)/, (msg) ->
    msg.send 'matched='+msg.match

I would like to be able to match:

blah blah blah ITEM=100 ITEM=200 ITEM=300 blah blah

However I only get the first match with above code:

match=blah blah blah ITEM=100 ITEM=200 ITEM=300 blah blah,ITEM=100

I can always just take the message and manually parse each line for each item, but it seems that using robot.hear should be able to do it.


Solution

  • Use the two-step method, but you can do some things to make it a little more concise:

    coffee> input = "blah blah blah ITEM=100 ITEM=200 ITEM=300 blah blah"
    'blah blah blah ITEM=100 ITEM=200 ITEM=300 blah blah'
    coffee> match = input.match /blah blah blah ((ITEM=\d+\s*)+) blah blah$/
    [ 'blah blah blah ITEM=100 ITEM=200 ITEM=300 blah blah',
      'ITEM=100 ITEM=200 ITEM=300',
      'ITEM=300',
      index: 0,
      input: 'blah blah blah ITEM=100 ITEM=200 ITEM=300 blah blah' ]
    coffee> match[1].match /(ITEM=\d+)/g
    [ 'ITEM=100',
      'ITEM=200',
      'ITEM=300' ]