re:match

Matches a regexp to a string

Prototype

start, end, substrings = re:match (string, pos, flags)

Description

This takes a regular expression object compiled previously with rex.new, and matches it against a target string.

The "pos" argument is optional, and specifies a 1-relative starting point for the match. If omitted, the whole string is tested. You can also supply a negative number to count from the right, eg. -10 would start 10 characters from the end of the string.

The "flags" argument is optional, and specifies execution flags, as described above.

Example:

re = rex.new ("(.+) goes (.+)")
s, e = re:match ("Nick goes East")
print (s, e) --> 1 14
If you are planning to do multiple matches against the same regular expression, it is faster to compile once only (ie. do rex.new once), and test multiple times.

However for once-off tests you can combine them both into the same line:

s, e = rex.new ("(.+) goes (.+)"):match ("Nick goes East")
print (s, e) --> 1 14
The third result returned is a table of capture patterns that have been matched.

Example:

re = rex.new ("(?P<who>.+) goes (?P<where>.+)")
s, e, t = re:match ("Nick goes East")
print (s, e) --> 1 14
table.foreach (t, print) --> see below
Output from table.foreach:

1 Nick
2 East
where East
who Nick

This shows that the 2 capture patterns (the things in round brackets) have been captured in the table as index 1 and 2 (first and second pattern) and also under named indices "where" and "who" because we used named capture patterns in the regular expression.

Lua functions

Topics