3

I know that you can't repeat match groups in Lua. For example, if I wanted to match the two successive "45"'s, I can't do:

print(string.find("some 4545 text", "(%d%d)+"))

which will print nil (no match found).

However, since find(...) doesn't report an error (for the invalid patterns "%" and "(%d" errors are produced), it leads me to believe the pattern "(%d%d)+" is a valid one.

If "(%d%d)+" is a valid pattern, what does it match? And if it isn't, is there a particular reason no error is produced?

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288

2 Answers2

5

"(%d%d)+" is a valid pattern. It matches for example "some 45+67 text" or "some 4567+ text" and captures "45" in the first case and "67" in the second.

Socken Puppe
  • 134
  • 3
  • Aha, the `+` simply becomes a literal instead of a meta character (that's very different from the regex/pattern-match engines I'm used to). Thanks! – Bart Kiers Jun 19 '12 at 10:51
  • The other regexes i know have this ambiguity: Parenthesis are used for grouping (there the + makes sense) and for captures. In lua patterns, there is no grouping, thus... But yeah, the manual could state that a bit more explicitly. – Socken Puppe Jun 20 '12 at 09:05
1

To match two successive occurrences of a string of digits, use "(%d+)%1".

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Thanks, although I knew that already. My question was what the pattern `"(%d%d)+"` is supposed to match (in case it is valid). – Bart Kiers Jun 19 '12 at 10:48