Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript regex not matching as intended

I'm trying to write a hubot script that answers to two different kinds of input. A user can either input the name of a stop for the local public transport or optionally postfix this with a delay.

The input can therefore be dvb zellescher weg or dvb albertplatz for the first option or dvb zellescher weg in 5 or dvb albertplatz in 10 for the second. ("dvb" here being the keyword for my script and "zellescher weg" and "albertplatz" being two examples for stop names)

On trying to match these with regex I'm running into an issue where a regex I've gotten to work on different testing sites (like regex101 which seems to be recommended here and does JS) won't work in my code. The regex for matching input without a number is /^dvb (\D*)$/ and I'm using /dvb\s+(.*)in (\d*)/ to match the cases where the user has entered a delay.

A minimal code example for my hubot that isn't matching for reasons unbeknownst to me looks like this:

robot.respond /^dvb (\D*)$/, (res) ->
    hst = res.match[1]
    res.send hst

Thanks for any help on this.

like image 612
Kilian Avatar asked Sep 28 '22 05:09

Kilian


1 Answers

According to the source respond code comments:

# Public: Adds a Listener that attempts to match incoming messages directed
# at the robot based on a Regex. All regexes treat patterns like they begin
# with a '^'

The regex from respond goes to respondPattern that escapes ^ and warns against using anchors:

if re[0] and re[0][0] is '^'
      @logger.warning \
        "Anchors don't work well with respond, perhaps you want to use 'hear'"

So, you need to either remove the ^, or use a .hear method that does not use any "smart" regex pre-processing:

hear: (regex, options, callback) ->
    @listeners.push new TextListener(@, regex, options, callback)
like image 127
Wiktor Stribiżew Avatar answered Oct 11 '22 16:10

Wiktor Stribiżew