[Home] [Downloads] [Search] [Help/forum]



Matches a regexp to a string


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


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.


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.


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.

See Also ...

Lua functions

re:exec - Matches a regexp to a string, returning offsets
re:gmatch - Matches a regexp to a string, applying a function
rex.flags - Returns a table of PCRE flags
rex.new - Compiles a regular expression


Lua base functions
Lua bc (big number) functions
Lua bit manipulation functions
Lua coroutine functions
Lua debug functions
Lua io functions
Lua LPEG library
Lua math functions
Lua os functions
Lua package functions
Lua PCRE regular expression functions
Lua script extensions
Lua string functions
Lua syntax
Lua table functions
Lua utilities
Scripting callbacks - plugins

(Help topic: lua=re:match)

Documentation contents page

Search ...

Enter a search string to find matching documentation.

Search for:   

Quick links: MUSHclient. MUSHclient help. Forum shortcuts. Posting templates. Lua modules. Lua documentation.

Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.


Written by Nick Gammon - 5K   profile for Nick Gammon on Stack Exchange, a network of free, community-driven Q&A sites   Marriage equality

Comments to: Gammon Software support
[RH click to get RSS URL] Forum RSS feed ( https://gammon.com.au/rss/forum.xml )

[Best viewed with any browser - 2K]    [Hosted at FutureQuest]