3

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Niccolo M.
  • 3,363
  • 2
  • 22
  • 39

1 Answers1

5

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.

stema
  • 90,351
  • 20
  • 107
  • 135
  • 2
    Nice answer. To make it clearer in case the OP is wondering, in `(\\.|.)` the order of the alternation is important, but since `?` is a greedy quantifier it will indeed always try `\\.` before trying `.` (`{0,1}` will try the `1` solution first too) – Robin Apr 07 '14 at 13:29
  • 2
    In Lua, `%1` is in the place of `$1`. Other than that, your pattern should work: `string.gsub("some\\astring", "(\\?.)", "[%1]")` – Yu Hao Apr 07 '14 at 13:35
  • Wow, thanks for the simple answer! (I hope I'm not the only one who sometimes fail to see the simple solutions...) – Niccolo M. Apr 07 '14 at 22:10