Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any Lua pattern alternative to the regex (\\.|.)?

There's a common idiom for traversing a string whose characters may be escaped with a backslash by using the regex (\\.|.), like this:

alert( "some\\astring".replace(/(\\.|.)/g, "[$1]") )

That's in JavaScript. This code changes the string some\astring to [s][o][m][e][\a][s][t][r][i][n][g].

I know that Lua patterns don't support the OR operator, so we can't translate this regular expression directly into a Lua pattern.

Yet, I was wondering: is there an alternative way to do this (traversing possibly-escaped characters) in Lua, using a Lua pattern?

like image 574
Niccolo M. Avatar asked Sep 15 '26 09:09

Niccolo M.


1 Answers

You can try

(\\?.)

and replace with [$1]

See it on Regexr.

? is a shortcut quantifier for 0 or 1 occurences, so the above pattern is matching a character and an optional backslash before. If ? is not working (I don't know lua) you can try {0,1} instead. That is the long version of the same.

like image 192
stema Avatar answered Sep 18 '26 03:09

stema