Mike's Regex Cheatsheet
basic metacharacters
?
is used for string that is optionally present
/colou?r/
matches "color" and "colour"
-
/color|colour/
matches either, just like previous example
/[a-z]*/
matches zero or more alphabet chars
/[a-z]+/
matches one or more alpha chars
/[^0-9]/
matches strings with NO digits
/^[0-9]/
matches strings that START with a digit
/[0-9]{1}/
matches a single digit
/[0-9]{1,}/
matches one digit or more
-
/[0-9]{2,4}/
matches 2,3 or 4 digits
/[0-9]{2}-[0-9]{2}-[0-9]{2,4}/
matches dates like mm-dd-yy and mm-dd-yyyy
/[\d]{2}-[\d]{2}-[\d]{2,4}/
this is same as previous, but using \d which matches digit chars
/\b[\d]/
- matches initial word boundary, via \b, which matches a digit, ex: "4chan"
/[\d]\b/
- matches digit at final word boundary, like "fab4"
/\S+@\S+?/
- matches abc@def" using \S which matches non-whitespace chars
simple examples
- back reference: we use \1 to match one more instance of whatever was matched in ()
/([a-z]+) +\1/
- literals can be denoted by using backslashes, like to search for period or question mark:
/127\.0\.0\.1/ or /who\?/
- dates, example format: mm/dd/yyyy
/^(0[1-9]|1[0-2])\/(0[1-9]|[12][0-9]|3[0-1])\/([12][0-9]{3})$/
- times with hour:min and optional am/pm
/^(1[0-2]|0?[1-9]):([0-5]?[0-9]) ( ?[AaPp][Mm])?$/
- IP address ex: n.n.n.n where 0 <= n <= 255, ignoring some invalid IP matches like 0.0.0.0
/^([0-9]{1,3}\.){3}([0-9]{1,3})$/
- simple URL matching protocol://domain.ext
/^(https?|s?ftp|file)://.+\.[a-z]{2,}$/
- case sensitive match: ?i, ex: match THE or the or The -
/the/i
- positive lookahead match: ?= ex: match passwords with length of 8-12 chars and upper, lower and numeric chars like abC1 or A2bc or 9rE9 -
/^(?=.{8,12})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*/
-
javascript
pattern.test(string)
array = pattern.exec(string)
array = string.match(patternString)