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?
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.