Regular expressions (regex or regexp) are a set of characters and symbols that are used to match and manipulate strings. They are often used to search, find and replace text, validate input, and perform other tasks related to text processing.

A super useful tool to learn and understand regexes is Regex tester.

Detailed examples

Getting TODO items

The input is

 <!--TODO:
 A random TODO Item
 -->
 
 Some additional text
 
 <!--TODO: Another TODO Item-->

The goal is to get A random TODO Item and Another TODO Item as a result. This can be achieved with /^<!--TODO:\n*(.*)\n*-->/gm.

Explanation:

  • ^ asserts position at the start of a line

  • <!--TODO: matches the characters <!--TODO: literally (case sensitive)

  • \n matches a line-feed (newline) character

    • * matches the previous token between zero and unlimited times, as many times as possible
  • 1st Capturing Group (.*)

    • . matches any character (except for line terminators)
    • * matches the previous token between zero and unlimited times, as many times as possible
  • \n matches a line-feed (newline) character

    • * matches the previous token between zero and unlimited times, as many times as possible
  • --> matches the characters --> literally (case sensitive)

  • Global pattern flags

    • g modifier: global. All matches (don’t return after the first match)
    • m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only the beginning and ending of a string)