Pwrcdr87
Pwrcdr87

Reputation: 965

Lua: string.gsub pattern(s) to permit multiple pattern replacement

This topic has been partially handled before by another user in thread: Lua string.gsub with Multiple Patterns

I'm having issues and I believe it is with my pattern (second) argument. Here is my example of the gsub code I'm trying to use:

local dateCode = "MMM/dd-YYYY:ss"

--dateCode = dateCode:gsub(".*", {["%/"] = "s", ["%-"] = "n", ["%:"] = "c"}) --original code but removed after @Etan's comments.
dateCode = dateCode:gsub(".*", {["/"] = "s", ["-"] = "n", [":"] = "c"})

print(dateCode)

MMM/dd-YYYY:ss  --printed

MMMsddnYYYYcss  --desired

I believe that I shouldn't be looking over all characters like I currently have it, but I'm not sure what pattern I should be using for the dateCode variable. The idea is to replace the keys with the first alpha character that it begins with.

Upvotes: 2

Views: 3146

Answers (1)

hjpotter92
hjpotter92

Reputation: 80639

Since you want a select set of characters to be replaces, put them in a character set as the pattern:

dateCode = dateCode:gsub("[/:-]", {["/"] = "s", ["-"] = "n", [":"] = "c"})

What happens currently is, with the pattern .* in place, it matches the entire string. Since the string "MMM/dd-YYYY:ss" has no indexed value in the hash table (second argument), no replacement actually occurs.

Upvotes: 3

Related Questions