Struggles with Regex

Recently, I’ve advanced to the “Bob” exercism, which deals with using regular expressions in Javascript. Regular expressions are a way to match character types in programming, useful for searching and/or replacing strings that share a certain pattern.

“Bob” involves making an object Bob that responds to inputs in the following manner:

  1. ‘Fine. Be that way!’ given no input or input in the form of spaces.
  2. ‘Sure.’ when faced with a question.
  3. ‘Whoa, chill out!’ when faced with any phrase in all capital letters.
  4. ‘Whatever.’ when anything else is said.

I first made a constructor to hold Bob’s responses:

Then, added the function hey() to the Bob prototype. This is the example of a regex that returns true whenever nothing is said to Bob.

^ and $ were included to indicate that the response had to start and end with a space or no space at all (indicated by the *, which modifies a regex such that it will return true with .test() if matches a character in input zero to infinite times).

I ran into some serious trouble trying to distinguish some of the test cases from Exercism, notably those that had all uppercase letters vs. those that only contained a few uppercase words. Rather than thinking more broadly, I kept trying to modify my regex such that it would match each specific case…

Thankfully, I came upon a few examples where more experienced programmers showed me how I could make my expressions MUCH more general. See below my final code:

This matched ALL 17 test cases!

Lesson learned: whenever I wanted to work with regex, I needed to make my expressions as general as possible and readable. For instance, I ran into considerable trouble when trying to define the “Shouting” response by using /\s[A-Z]{2,}/.test(input), which would always fail in cases where there were lower-case words. By changing this to input.toUpperCase() === input, I was able to match only uppercase sentences.

Like what you read? Give Justin Yeh a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.