Regex tester

Share your scripts and packages with other Mudlet users.
Post Reply
chrio
Posts: 73
Joined: Mon Aug 22, 2016 11:34 am

Regex tester

Post by chrio »

Since regular expressions are used a lot in triggers I made a script to help with testing patterns:
Code: [show] | [select all] lua
------------------------------
--        regex test        --
------------------------------

function retest(regexPattern, stringToTest)

	local col="<orange>"
	retestMatches = nil

	local tt = tempRegexTrigger(regexPattern, [[retestMatches=matches]]) 
	cecho(col.."Regex test\n---------------------\n")
	cecho(col.."pattern:\n<white>" .. regexPattern )
	feedTriggers("\n")
	cecho(col.."string:")
	feedTriggers( stringToTest .. "\n")
	killTrigger(tt)

	echo("\n")
	if(retestMatches) then
		for k,v in ipairs(retestMatches) do
			cecho(col.."matches["..k.."]:  <white>" .. v .. "\n")
		end
	else
		echo("String did NOT match the pattern.\n\n")
	end

	retestMatches = nil
end
Just add it to a new script and save it, then you can test patterns from the command line like this:
lua retest( <pattern>, <string to test>)

example:
lua retest([[^\*\* (\d+)/(\d+) HP (\d+)/.*]], [[** 123/234 HP 44/88 SP blahblah]])
output:

Code: Select all

Regex test
---------------------
pattern:
^\*\* (\d+)/(\d+) HP (\d+)/.*

string:
** 123/234 HP 44/88 SP blahblah

matches[1]:  ** 123/234 HP 44/88 SP blahblah
matches[2]:  123
matches[3]:  234
matches[4]:  44
When using it, I reccomend that you encase the strings with [[ ]] instead of quotes, otherwise you need to use \\ instead of \ everywhere in the pattern.

You can also call the function within your scripts, that may be easier to read.
Again, set the values using [[ ]] in that case:

Code: Select all

local p = [[^(\w+) tells you: (.*)$]]
local s = [[NameHere tells you: Hello there!]]
retest(p,s)

...output...

matches[1]:  NameHere tells you: Hello there!
matches[2]:  NameHere
matches[3]:  Hello there!
Let me know if you have any questions or suggestions on improvements.

User avatar
SlySven
Posts: 1019
Joined: Mon Mar 04, 2013 3:40 pm
Location: Deepest Wiltshire, UK
Discord: SlySven#2703

Re: Regex tester

Post by SlySven »

Just a hint for anyone - when you enter a script (or other things like a key/alias/alias etc.) into the edit window on the (middle) right of the editor dialogue: if you make the first line a lua comment (i.e. it begins with "--") then THAT line (or at least the beginning of it) is included in error messages related to that script (or whatever) in the floating central debug console and/or the editor errors window (lower right) of the editor if it is showing. This can make it easier to work out in complex systems where an error is actually occurring...

So, in the above example I'd suggest changing:

Code: Select all

------------------------------
--        regex test        --
------------------------------
to:

Code: Select all

-- regex test
------------------------------

Post Reply