DaveInDev
DaveInDev

Reputation: 27

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

Upvotes: 0

Views: 636

Answers (2)

DaveInDev
DaveInDev

Reputation: 27

I ended up doing a match("!([-+]?%d+)") and if there is no result, I do a find("!") to handle the lonely "!" case.

Too bad that Lua does not have | for or...

Upvotes: 1

Luatic
Luatic

Reputation: 11171

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

Upvotes: 2

Related Questions