Show Menu

Lua string patterns Cheat Sheet by

Reference to Lua string matching patterns

Function Calls

string.find(string, pattern, startindex, nopattern)   # returns indices
string.gmatch(string, pattern, startindex)            # creates a iterator returning all matches
string.match(string, pattern, startindex)             # returns the matched string
string.gsub(string, pattern, replace)                 # replace can be a function or table, can use %n to use n-th captured element

Pattern Syntax

A pattern is a list of consec­utive pattern items.
Adding a
at the start of a pattern anchors it to the start of the string, and
at the end. Otherwise, they have no special meaning.

Character Classes

, where is is not
can be anything
Lowercase letters
Uppercase characters (same as
Hexade­cimal digits (same as
Alphan­umeric characters (same as
Space characters
Punctu­ation characters
Printable characters (not including space)
Control characters
Union of all characters in the set, with possible character classes and RegEx style ranges
Inverse of
The uppercase variant represents the inverse of the set, so
The dash can be included in sets by positi­oning it as the first or last character, and the square bracket as the first. Or just use a escape.

Pattern Item

A pattern item can be any of the following:
Character Class
1 of the class
Character Class with *
≥0 of the class, longest possible
Character Class with -
≥0 of the class, shortest possible
Character Class with +
≥1 of the class
Character Class with ?
1 | 0 of the class
Matches the n-th captured string
Frontier pattern
Balanced match
Frontier patterns ::: They match an empty string
that does not precede with the set, but does succeed with the set.
Balanced match ::: They match until the pair balances out. For example,
matches entirely
(The quick br((own f>ox jum>ped over the lazy dog>


Captures allow you specify groups. They are defined with parent­heses, and they can include any valid pattern within.

Using pattern reference we can match the same character. Note that it is not reusing the pattern, it is reusing what the pattern matched.
is NOT the same as

You can also use captures to return results from
after the indices, multiple results in
, and use in the replac­ement string in

The empty capture
represents the current index in the string.


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Regular Expressions Cheat Sheet
          Perl Reference Card Cheat Sheet

          More Cheat Sheets by ambigious

          Lua string.format Cheat Sheet