Hubot matching on multiple tokens per line?

泪湿孤枕 提交于 2019-12-24 15:03:12

问题


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.



来源:https://stackoverflow.com/questions/30673246/hubot-matching-on-multiple-tokens-per-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!