Interested in improving this site? Please check the To Do page.
Back to Regular Expression (re) Verbs
re.extract
Extracts all matches of a pattern in the target string into a list.
Syntax
re.extract (cp, s, groups)
Params
- cp is a binary param containing the compiled pattern that was returned by a call to “re.compile”.
- s is a string param containing the target string.
- groups is an optional list param containing references to capturing parenthesis. Defaults to an empty list.
Returns
List of matched parts of the target string.
Examples
local (cp = re.compile ("([^.]+(silly|stupid)[^.]+\\.)"))
local (s = "This is a silly test. This is only a stupid test.")
re.extract (cp, s)
{“This is a silly test.”, “This is only a stupid test.”}
re.extract (cp, s, groups: {2})
{“silly”, “stupid”}
re.extract (cp, s, groups: {1, 2})
{{“This is a silly test.”, “silly”}, {“This is only a stupid test.”, “stupid”}}
Notes
- The groups parameter determines what will actually be added to the result list for each match. The elements of the groups list can either be numbers referring to capturing parentheses or strings specifying the names of capturing parentheses.
- If the groups parameter is unspecified or the empty list, the complete part of the target string that was matched will be added as a string element to the result list.
- If the groups parameter is a list containing a single element, the substring captured by the referenced parentheses will be added as a string element to the result list.
- If the groups parameter is a list containing more than one element, a list of the substrings captured by the referenced parentheses will be added to the result list, i.e. in this case a list of lists of strings is returned.