Search code examples
stringlualua-patterns

Format string to fit pattern in Lua?


Say I have a pattern, and a string:

String  = "ABCDEF"
Pattern = "%w%w%w - %w%w%w"

How can I make String match the format of Pattern, so it becomes "ABC - DEF"?


Solution

  • Use string.gsub:

    string.gsub("ABCDEF", "(%w%w%w)(%w%w%w)", "%1 - %2")
    

    Note that this would replaces all the occurrences of the pattern.