Categories: JavaScript

Botkit and Regular Expressions

Regex has never been my favorite part of writing code. I get that some people geek out on it and bless their hearts. For me, it’s an annoyance that is best left abstracted out of my daily coding experience. Thankfully, I am not alone. There are plenty of sites and programs that generate regular expression sequences for all your pattern matching needs.

Today, I used regular-expressions.info and Mozilla’s JavaScript Regular Expressions Guide to write some code that helps a SlackBot take a date from a user and save it.

Botkit‘s controller.hears method takes a regex as a parameter and returns an array containing the matches. The first element of the array is the full input string from the user.

So, this regular expression will search for a date in the format MM/DD/YYYY and return four elements in an array: the full string, the month, the day, and the year. The parenthesis tell the interpreter to capture the matches.

'(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.]([1-2][0-9][0-9][0-9])'

screen-shot-2016-09-08-at-12-42-08-pm

That’s pretty cool. I’ve added a bit at the front that matches the word “Set” followed by any number of characters and then continues on capturing the date.

^[S|s]et.*

The caret makes sure it’s at the very beginning of the input. [S|s] lets the user omit capitalization. and dot-asterisk is the wildcard for any number of characters. The whole thing together gives us this output:

screen-shot-2016-09-08-at-1-16-20-pm

That’s pretty cool, but let’s get even more literal.

[S|s]et.*date.*

That lets us say things like, “Set the date to 09-09-2012” but not “Set the pickles to 09-09-2012” which is what people would expect from a Very Smart Slackbot. It also lets there be some leeway in a user’s input, so “Set date 09-09-2012” works as well as “Hey, Rememberbot, can you set a date for me? Don’t let me forget 09-09-2012, thanks.”

screen-shot-2016-09-08-at-1-28-04-pm

These examples remind me why people who write code are the worst testers of that code. When testing code to make sure it’s executing correctly, I use the quickest way to enter data, which often means repeating the same test data. That leads to errors that slip through to (hopefully) testers and possibly to end users as shipping bugs.

Article info