Skip to content

Instantly share code, notes, and snippets.

@irlnathan
Last active March 18, 2016 21:09
Show Gist options
  • Save irlnathan/73851931dcd39d18a5f7 to your computer and use it in GitHub Desktop.
Save irlnathan/73851931dcd39d18a5f7 to your computer and use it in GitHub Desktop.
Regular Expression Cheat Sheet

I'm documenting the .match() method for JavaScript, there are others.

  • / by itself indicates the beginning and the end of the regex
  • /^ combined with $/ means “ match the entire string” (rather than matching substrings that begin and/or end somewhere in the middle)
  • the i suffix is a modifier indicating that the match should be done in a case-insensitive manner
  • [a-z0-9\-] matches a character which is either a number, letter or dash (works for capital letters because of the i at the end
  • the + indicates the match one or more of whatever came before
  • if you put a caret (^) inside of the match expression capturer thingamajig, it reverses the meaning
// Match any 3 character string where the first character is a number from 1-9 and the second two characters are numbers from 0-9.
var IS_3_DIGIT_FINITE_INTEGER = /^[1-9][0-9][0-9]$/

// Match any 3 character string where the first character is ANYTHING OTHER THAN a number from 1-9, and the second two characters are ANYTHING OTHER THAN numbers from 0-9.
var OPPOSITE_OF_THAT_SORT_OF = /^[^1-9][^0-9][^0-9]$/
if (!_.isString(req.param('username')) || req.param('username').match(/[^a-z0-9]/i) || req.param('username').length === 0) {
  return res.badRequest('Invalid username');
}
// …

that says:

  • if it is not a string
  • OR it contains ANY characters other than letters or digits
  • OR it is the empty string then it is invalid.

The original if statement said:

  • if it is not a string
  • OR it IS NOT a string CONSISTING ENTIRELY of one or more characters which are all either letters or digits then it is invalid.
  • remember ^ means two different things
  • /^ means the start of the string
  • [^abc] means a single character which is not a, b, or c
  • + means one or more of the previous character or match group thing
  • * means zero or more of the previous character or bracket match group thing
  • . means any character
  • Use \ to escape those things (as well as brackets, parentheses, and slashes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment