2
votes

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.

1
What is your desired output here? MMMsddnYYYYcss? The keys in the gsub replacement need to equal the captured bits of the string that the pattern matches. You don't have % in your input so none of your keys can possibly match. - Etan Reisner
@EtanReisner you are correct. That is the desired output. I erroneously used the % as escape characters in my keys. Thanks. Once removed, still does not appear to provide the desired result. - Pwrcdr87
Think about what you are matching with your pattern. What will the "result" of the match be? That is what gsub looks up in the table argument. So if you want to replace just those characters then you need to, individually, match just those characters. - Etan Reisner
@EtanReisner UGHH..... thank you for spelling it out of me. %p...... I'll update my post to show the correct pattern. - Pwrcdr87
Don't update the post. If you have a solution add an answer and accept it. - Etan Reisner

1 Answers

3
votes

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.