Skip to content

Instantly share code, notes, and snippets.

@withchristopher
Last active September 24, 2020 12:45
Show Gist options
  • Save withchristopher/78d5b00effdc406d238208692077f047 to your computer and use it in GitHub Desktop.
Save withchristopher/78d5b00effdc406d238208692077f047 to your computer and use it in GitHub Desktop.
Regular expressions are ubiquitous in modern programming. Here is a guide to help you navigate through the what, how and why

Regular Expression in Javascript

Regular Expressions are everywhere. This guide takes you through some of the most commonly found regex, how to read and write them into your codebase.

Summary

This guide will cover Javascript regex

Questions to ask yourself before designing regular expressions:

  • Is the content I am looking for in a pattern or more dynamic?

Table of Contents

Regex Components

Anchors

Quantifiers

Quantifiers define quantities and indicate numbers of characters or expressions to match. The characters used are: n+ n* n? n{x} n{,x} n{x,y}. Here are examples:

  • /ab+/.test('abbcdab') // matches "abb"
  • /bb*/.test('abbcdab') // matches "bb"
  • /b{2,}/.test('abbcdab') // matches "bb"
  • /a{1,3}/.test('bbcdaaab') // matches "aa"

OR Operator

Character Classes

Flags

Flag are also called modifiers because they modify the output of a regular expression. Flags can be used in any order or combination:

Flag Description
i Case insensitive: Sets matching to be case-insensitive
g Global Search: Search for a pattern throughout the input string.
m Multiline:Anchor meta character works on each line.

Grouping and Capturing

Bracket Expressions

Greedy and Lazy Match

Boundaries

Boundaries indicate the beginning and end of lines and words. The characters used are ^$\b\B. Here are examples:

  • /^An/.test('An Apple) // matches "An"
  • /App$/.test('Mobile App') // matches "App"
  • /un\b/.test('Sun') // matches "un"
  • /\Bon/.test('Moon') // matches "on"

Back-references

Look-ahead and Look-behind

AKA. Assertions (which also include conditional expressions)

Note that the ? character is also used as a quantifier

Characters Example Descriptions
x(?=y) /Atta(?=shah)/ Look-ahead assertion. Matches x only if it is followed by y.
x(?!y) /\d+(?!\.)/ Negative look-ahead assertion. Matches x only if it is NOT followed by y.
(?<=y)x /(?<=shah)Atta/ Look-behind assertion. Matches x only if it is preceeded by y.
(?<!y)x /(?<!-)\d+/ Negative look-behind assertion. Matches x only if it is NOT preceeded by y.

Author

Gist created in September 2020 by Chris Maxwell. Check out my bio page here: https://withchristopher.github.io/csmportfolio/ Checkout my github here: https://github.com/withchristopher Follow me on Twitter here: https://twitter.com/withchristopher

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment