LoginSignup
12
12

More than 5 years have passed since last update.

robot.respondでmsg.matchを使う場合は単一でもキーワードを()で囲まなければならない

Posted at

結論

robot.hearの場合はいつでもmsg.match[0]で入力を取得できるが、
robot.respondの場合はmsg.match[0]には呼び出すためのHubot名まで入ってしまい、()で囲まなければHubot名が取り除かれた入力のmsg.match[1]が生成されない。

正規表現

respond

module.exports = (robot) ->
    robot.respond /.*/i, (msg) ->
        console.log(msg.match)
Hubot> hubot aaa
[ 'hubot aaa', index: 0, input: 'hubot aaa' ]
module.exports = (robot) ->
    robot.respond /(.*)/i, (msg) ->
        console.log(msg.match)
Hubot> hubot ttt
[ 'hubot ttt', 'ttt', index: 0, input: 'hubot ttt' ]

hear

module.exports = (robot) ->
    robot.hear /.*/i, (msg) ->
        console.log(msg.match)
Hubot> ccc
[ 'ccc', index: 0, input: 'ccc' ]
module.exports = (robot) ->
    robot.hear /(.*)/i, (msg) ->
        console.log(msg.match)
Hubot> bbb
[ 'bbb', 'bbb', index: 0, input: 'bbb' ]

完全一致

respond

module.exports = (robot) ->
    robot.respond /test1/i, (msg) ->
        console.log(msg.match)
Hubot> hubot test1
[ 'hubot test1', index: 0, input: 'hubot test1' ]
module.exports = (robot) ->
    robot.respond /(test2)/i, (msg) ->
        console.log(msg.match)
Hubot> hubot test2
[ 'hubot test2', 'test2', index: 0, input: 'hubot test2' ]

hear

module.exports = (robot) ->
    robot.hear /test3/i, (msg) ->
        console.log(msg.match)
Hubot> test3
[ 'test3', index: 0, input: 'test3' ]
module.exports = (robot) ->
    robot.hear /(test4)/i, (msg) ->
        console.log(msg.match)
Hubot> test4
[ 'test4', 'test4', index: 0, input: 'test4' ]

躓き経緯

今までは/hoge (.*)/のような使い方しか見てなかったので、正規表現のみの場合は()は不要と考えていたし、robot.hearで正規表現だけのものでは()が無いことがあった。
robot.respondかつ正規表現のみの入力を利用する場面が今回が初だった。

12
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12