Online regex debugger:

Regular Expressions 101 - https://regex101.com/

Charsets:

  • [abc] will match a, b, and c (every occurrence of each letter)
  • [abc]zz (or) [a-c]zz will match azz, bzz, and czz.
  • [a-cx-z]zz will match azz, bzz, czz, xzz, yzz, and zzz.
  • [a-zA-Z] will match any single letter (lowercase or uppercase).

Exclude character:

  • [^k]ing will match ring, sing, $ing, but not king.
  • [^a-c]at fat and hat, but not bat or cat.
  • [a-cx-z]zz will match azz, bzz, czz, xzz, yzz, and zzz.
  • [a-zA-Z] will match any single letter (lowercase or uppercase).

Wildcards and optional characters:

Wildcards:

  • a.c will match aac, abc, a0c, a!c, and so on. (use \ to escape)
  • a.*c will match everything between first occurrence of a and last occurrence of c

Optional characters:

  • abc? will match ab and abc, since c is optional.

Metacharacters and repetitions:

Metacharacters:

  • \d matches a digit 0-9
  • \D matches a non-digit, like A or @ etc.
  • \w matches an alphanumeric character, like a or 4 etc. (NOTE: _ is included in \w not in \W)
  • \W matches a non-alphanumeric character, like ! or # (A.K.A Special Characters)
  • \s matches any whitespace characters. (spaces, tabs, and line breaks)
  • \S matches everything else except whitespace characters. (alphanumeric characters and symbols)

Repetitions:

  • z{2} will match exactly zz.
  • {12} exactly 12 times.
  • {1,5} 1 to 5 times.
  • {2,} 2 or more times.
  • * 0 or more times.
  • + 1 or more times.

Starts with or Ends with:

  • ^ Starts with
    ex: ^abc search for a line that starts with abc.

  • $ Ends with
    ex: abc$ search for a line that ends with abc.
  • NOTE: The ^ caret symbol is used to exclude a charset when enclosed in [square brackets], but when it's used without square brackets it specifies the beginning of a word or a line.

Groups and OR Operator:

    Anything enclosed between () are called groups. They capture the text matched by the regex inside them into a numbered group that can be reused with a numbered backreference.

    ex: during the (day|night) will match both of these sentences: 'during the day' and 'during the night'.

    ex: (no){5} will match the sentence 'nonononono'.