Search code examples
lualua-patterns

Matching a pattern in Lua


I'm trying to match a string which is 9 characters long and will always have digits.

The pattern I am trying to match is to see if the string is all 0s or all 1s or all 2s and so on upto all 9s.

Can someone help me write this. I just had to consider 0s and 9s and i hard coded those and it works fine. But surely there's an easier way to do this.

Can someone help please?


Solution

  • Try this pattern: ((%d)%2%2%2%2%2%2%2%2).

    As Etan mentioned in a comment, you can also use query a table:

    allowed={ ["000000000""]=true, ["111111111""]=true, ..., ["999999999"]=true }

    Then s matches one of the allowed patterns if allowed[s] is true.