Hubot matching on multiple tokens per line?

2019-08-02 13:51发布

问题:

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.

回答1:

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' ]


回答2:

You can avoid the intermediate match by using the g flag on the regex passed to hear. For example:

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

All the matches are then available in msg.match.