Search code examples
stringluastring-matchinggsublua-patterns

Lua: RegEx to Pattern


Simple problem...I need to turn this RegEx pattern...

"\[\"([0-9]+)\"\]"

into a Lua pattern.

I am doing this to replace a bunch ["X"] lines with just [X] in a string where X is any number from -∞ or +∞...so that's about the only limitation. I need to port this to Lua patterns so I can use it in String.gsub.

Find: "\[\"([0-9]+)\"\]"

Also, how do I just remove the " " around the number? I need a pattern for that. If someone could help me out, I would appreciate it.


Solution

  • You could try like this.

    > f = "foo [\"12\"] bar"
    > x = string.gsub(f, "%[\"(%d+)\"%]", "[%1]")
    > print(f)
    foo ["12"] bar
    > print(x)
    foo [12] bar
    

    \d which matches any digits would be represented as %d in lua.