Question about regular expressions in lua

Posted by Sandmaster on Mon 28 Oct 2024 01:44 AM — 2 posts, 5,899 views.

#0
Hello.
I'm trying to use some regex on mushclient with lua.
Everything seems to be working fine except the backslash character which I'm having issues about.
The manual says one of the features of backslash character is to remove any special meaning which the following character might have.
For example, if I write \* it means litteral * not an repeatition operator.
But the pcre library in mushclient doesn't seem to be working in this way.
If I write $rex.new("\*") in mushclient, I get a nothing to repeat error which might be an indication that mushclient is ignoring backslash in this context.
If I write rex.new("\[.*") I get an error about unterminated character class which tells me that mushclient just ignored \ and parsed [ as a metacharacter.
I'm currently using mushclient 5.06.
Any help on resolving this issue would be greatly appreciated.
Australia Forum Administrator #1
Lua itself treats a backslash as escaping special characters, so you need two backslashes if you want a backslash to be passed to the regexp module.

Alternatively you can use "long string literals" which do not recognise backslashes. So your options are:


re = rex.new ([=[\*+]=])
s, e = re:match ("Hi there **** everyone!")
print (s, e) --> 10 13


The long literal there matches on backslash-asterisk, that is, an asterisk, and the plus sign means one or more asterisks.

Or, using normal literals:


re = rex.new ("\\*+")
s, e = re:match ("Hi there **** everyone!")
print (s, e) --> 10 13





Long literals


A long literal is basically two square brackets with optional "=" symbols between them (in case you need to have two square brackets in a row in your literal).

eg.


print [[hi there]]
print [=[hi there]=]
print [==[hi there]==]


They can also span multiple lines, eg.


print [[Hi there,
I hope you are well.
Take care.]]





References


https://gammon.com.au/scripts/doc.php?lua=re:match

https://gammon.com.au/scripts/doc.php?lua=string%20literals