WoWInterface

WoWInterface (https://www.wowinterface.com/forums/index.php)
-   Lua/XML Help (https://www.wowinterface.com/forums/forumdisplay.php?f=16)
-   -   Pattern matching is my Kryptonite! (https://www.wowinterface.com/forums/showthread.php?t=56976)

myrroddin 01-12-19 11:43 AM

Pattern matching is my Kryptonite!
 
I am writing an external AddOn that converts invalid itemID lists into valid ones for TradeSkillMaster. However, for all that I have been reading on wowpedia.org and the official Lua documentation, I am stuck on matching exactly what I want in strings.

These are valid for TSM:
  • "i:82977"
  • "i:82977,i:10368"
While these are not valid:
  • "82977"
  • "82977,10368"
TSM requires itemIDs in the format "i:12345" and comma seperated if there are more than one. Okay, great. I can use string.gmatch (I don't care about what position the numbers are, so I'm not using string.match) like so:
Code:

local maybe_valid = string.gmatch(myString, "%d+$"
But that will match both examples above, valid and not valid. That won't work. How do I force the match to start at the first character of the string?

Checking if it is valid is easy, I think.
Code:

local valid = string.gmatch(myString, "i:%d+$"
The reason for knowing the difference is that after finding invalid strings, I will use string.gsub(myString, ",", ",i:") to fix them. Clearly I don't want to fix a string that is already valid.

myrroddin 01-12-19 11:51 AM

Would the following work, or does this need to be more complex?
Code:

local valid = string.gmatch(myString, "i:%d+$")
if not valid then
    myString = string.gsub(myString, ",", ",i:")
    myString = "i:" .. myString
end


Fizzlemizz 01-12-19 12:17 PM

It's not my forte so this is probably not very efficient if it does work.


Code:

local valid = string.gsub(myString, "[i:]+[0-9]+", replaceString)

myrroddin 01-12-19 12:50 PM

As for finding valid and invalid (turns out I need both, but need to know the difference) this might work:
Code:

local valid = true
for w in string.gmatch(text_store, "%d+") do
    if string.gmatch(w, "i:%d+") then
        valid = true
    else
        valid = false
        break -- we only need to find one incorrect itemID. no point in continuing
    end
end


krowbar71 01-12-19 01:21 PM

How about making everything wrong and fixing it all:

Code:

s = "I:1234,3450,i:9867"
s1 = string.gsub(string.gsub(s, "[iI]:", ""), "(%d+)", "i:%1")
print(s1)
i:1234,i:3450,i:9867

:rolleyes:

myrroddin 01-12-19 01:50 PM

Quote:

Originally Posted by krowbar71 (Post 331370)
How about making everything wrong and fixing it all:

Code:

s = "I:1234,3450,i:9867"
s1 = string.gsub(string.gsub(s, "[iI]:", ""), "(%d+)", "i:%1")
print(s1)
i:1234,i:3450,i:9867

:rolleyes:

Damn... :eek:


All times are GMT -6. The time now is 05:26 PM.

vBulletin © 2020, Jelsoft Enterprises Ltd
© 2004 - 2020 MMOUI