Module regex
Regular expressions.
The standard Lua library provides a handful of functions to deal with strings using “patterns”. Lua patterns, however, aren’t as powerful as the Regular Expressions many programmers have come to expect.
To fill this void, we also provide real, Perl-compatible regular
expressions (henceforth: PCRE) for you to use in your Lua code. The API
for this facility mimics the standard Lua API so you don’t need to learn
anything new. These regex-compatible functions have p_
prefixed to
their names. They're also available under the regexp namespace without
this prefix.
For example, instead of:
local first, last = s:match "(%w+) (%w+)" -- also available as: -- local first, last = string.match(s, "(%w+) (%w+)")
do:
local first, last = s:p_match "(\\w+) (\\w+)" -- also available as: -- local first, last = regex.match(s, "(\\w+) (\\w+)")
for the PCRE version.
Specifying regular expressions
There are three ways to specify a regular expression:
(1) As a string:
if file_extension:p_match "jpe?g" then ...
(2) As a table whose first element is a string and whose second element is a flags string:
if file_extension:p_match {"jpe?g","i"} then ...
(3) As a compiled regex object:
local picture = regex.compile {"jpe?g","i"} ... if file_extension:p_match(picture) then ...
Functions
regex.compile(regex) | Compiles a regular expression. |
find(s, regex[, init]) | Searches in a string. |
gmatch(s, regex) | Matches globally. |
gsub(s, regex, repl) | Performs a global search/replace on a string. |
match(s, regex[, init]) | Searches in a string. |
split(s, regex[, limit]) | Splits a string. |
tsplit(s, regex[, limit]) | Splits a string into a table. |
Functions
- regex.compile(regex)
-
Compiles a regular expression.
The regex parameter may be in any of the three forms specified in “Specifying regular expressions”. If regex is already a compiled regex object, the function simply returns the same object.
- find(s, regex[, init])
-
Searches in a string.
Like string.find but uses a regular expression.
- gmatch(s, regex)
-
Matches globally.
Like string.gmatch but uses a regular expression.
- gsub(s, regex, repl)
-
Performs a global search/replace on a string.
Like string.gsub but uses a regular expression.
- match(s, regex[, init])
-
Searches in a string.
Like string.match but uses a regular expression.
- split(s, regex[, limit])
-
Splits a string.
If regex contains captures, these are returned as well.
local s = "flavor = sweet" local name, value = s:p_split "\\s*=\\s*"
Use limit to set the maximum number of fields returned. The maximum possible value for limit is 12; use tsplit instead if this maximum restricts you.
- tsplit(s, regex[, limit])
-
Splits a string into a table.
Like split but the results are returned as a table. There’s no restriction on limit.