Regex
The Regex module is available via require "pluto:regex" and provides Soup's flavor of the popular string matching language.
regex.new
Parses a pattern and creates an instance for it.
Parameters
- The regex to be compiled. Note that this must be a full pattern with a start and end delimiter (commonly
/). Flags may optionally be present after the end delimiter.
Returns
A pattern instance.
regex.match
Attempts to match a pattern instance.
Parameters
- The pattern instance.
Returns
A table with an index/key for each matching group or nil if no matches.
plutolocal regex = require "pluto:regex"local pattern = new regex [[/^the (?:(.+) )?one$/]]print(dumpvar(pattern:match("the one")))--> {--> [0] = string(7) "the one",--> }print(dumpvar(pattern:match("the chosen one")))--> {--> [1] = string(6) "chosen",--> [0] = string(14) "the chosen one",--> }print(pattern:match("not the one"))--> nil
The overall pattern match is in index 0, and in this case there is only the 1 capturing group, that being (.+).
Capture group names will be used if available:
plutolocal regex = require "pluto:regex"local pattern = new regex [[/^the (?:(?'what'.+) )?one$/]]print(dumpvar(pattern:match("the chosen one")))--> {--> [0] = string(14) "the chosen one",--> ["what"] = string(6) "chosen",--> }
regex.search
Looks for a match of the regex in a string.
Parameters
- The pattern instance.
- The string to search in.
- The offset to start searching at. Defaults to 1.
Returns
On success:
- The start offset.
- The end offset.
On failure: Nil.
plutolocal regex = require "pluto:regex"local pattern = new regex [[/[A-Z]/]]print(pattern:search("Hello World")) -- 1, 2print(pattern:search("Hello World", 2)) -- 7, 8print(pattern:search("Hello World", 8)) -- nil
regex.replace
Replaces the first or all matches in a string, depending on the 'g' flag.
Parameters
- The pattern instance.
- The string to search in.
- The replacement string.
Returns
The new string.
Replace first matchplutolocal regex = require "pluto:regex"local r = new regex [[/[0-9]+/]]print(r:replace("I have 3 apples and 5 bananas.", "2")) --> I have 2 apples and 5 bananas.
Replace all matchesplutolocal regex = require "pluto:regex"local r = new regex [[/[0-9]+/g]]print(r:replace("I have 3 apples and 5 bananas.", "2")) --> I have 2 apples and 2 bananas.
regex.substitute
Substitutes the first or all matches in a string, depending on the 'g' flag.
Parameters
- The pattern instance.
- The string to search in.
- The substitution string. The substitution can reference capturing groups by their index, e.g.
$1for capturing group 1. Use$$to produce$.
Returns
The new string.
plutolocal regex = require "pluto:regex"local r = new regex [[/.+ (.+)/]]print(r:substitute("hello earth", "welcome to $1")) --> welcome to earth