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:

    • The start-of-string anchor ^ is misplaced (and thus treated as a character); the pattern anchor for end-of-string $ is missing (thus the pattern only matching part of the string would be allowed).
    • You're not allowing an empty number: %d+ requires at least one digit.

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

    • ^ and $ anchors: Match the full string, from start to end.
    • !: Match the prefix.
    • (: Start capture.
    • [-+]?: Match an optional sign.
    • %d*: Match zero or more digits.
    • ): End capture.

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