0

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
DaveInDev
  • 27
  • 8

2 Answers2

2

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

Luatic
  • 8,513
  • 2
  • 13
  • 34
  • Thanks. - I forgot to say that I'm searching this pattern anywhere in a big string. So maybe I do not need any ^ or $ ? - your solution is almost perfect, but it recognizes "!-" or "!+" which should not be allowed... Is there a way to write something like (expr1) or (expr2) ? So it could be "!([-+]?%d+)" OR "!()". And the second would return an empty string... – DaveInDev Oct 27 '22 at 15:24
  • You **must** remove the anchors `^` and `$` if you're searching in a string, yes. Unfortunately Lua patterns have no "or" (alternation/choice, usually denoted by the pipe `|`) operator. You'll have to add additional Lua code to check for these patterns, such as calling `string.match` two times with two different patterns. – Luatic Oct 27 '22 at 16:25
1

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

andrewJames
  • 19,570
  • 8
  • 19
  • 51
DaveInDev
  • 27
  • 8