luanumberslua-patterns

Regex with optional number and leading char ? (lua match)


I'm a beginner with regex and I'd like (for string.match() under lua) a regex that would recognize a positive or negative number prefixed by a special character (example : "!"). Example :

"!1" -> "1"
"!-2"  ->  "-2"
"!+3"  ->  "+3"
"!"  ->  ""

I tried

!(^[-+]?%d+)

but it does not work...


Solution

  • Your pattern only contains minor mistakes:

    Fixing all of these, you get ^!([-+]?%d*)$. Explanation:

    Note that this pattern will also accept !+ or !-.