Lua Pattern matching


  • string.find(str, pattern [, init [, plain]]) -- Returns start and end index of match in str

  • string.match(str, pattern [, index]) -- Matches a pattern once (starting at index)

  • string.gmatch(str, pattern) -- Returns a function that iterates through all matches in str

  • string.gsub(str, pattern, repl [, n]) -- Replaces substrings (up to a max of n times)

  • . represents all characters

  • %a represents all letters

  • %l represents all lowercase letters

  • %u represents all uppercase letters

  • %d represents all digits

  • %x represents all hexadecimal digits

  • %s represents all whitespace characters

  • %p represents all punctuation characters

  • %g represents all printable characters except space

  • %c represents all control characters

  • [set] represents the class which is the union of all characters in set.

  • [^set] represents the complement of set

  • * greedy match 0 or more occurrences of previous character class

  • + greedy match 1 or more occurrences of previous character class

  • - lazy match 0 or more occurrences of previous character class

  • ? match exactly 0 or 1 occurrence of previous character class


Throughout some examples, the notation (<string literal>):function <string literal> is used, which is equivalent to string.function(<string literal>, <string literal>) because all strings have a metatable with the __index field set to the string table.