I have a string for example CatCook
and i am trying to split it by the capital letters. I tried doing this:
local str = ("CatCook"):split("%u") print(str)
Which %u should split it by the capitals? Or am i completely wrong? It still returns CatCook
while i would like it to return Cat Cook
. How would i do it?
Thanks, kirda
So apparently i found about using brackets in patterns and created 2 lines method
local str = "ThisWillSplitThisStringBySpacesIThink" str = string.gsub(str, "(%u)", " %1") -- using brackets it allows third argument to access it by doing %1 (1 since it's the first bracket) and you can add TO or AFTER the letter instead of chaning it str = string.sub(str, 2, -1) -- Removes first space (idk how to remove it otherwise) print(str)
I randomly found similar thing in comma_value converter at the bottom of this
Sorry for the late response. Let's break this down to make it simpler. When using the %u
identifier, you're finding the first instance in which a capital letter occurs. This is helpful, but not in your case. Why? Because the interpreter is going to see the capital C in Cat and stop searching.
So let's be clear. You aren't searching for every capital letter. You're searching for every instance in which a capital letter is preceded by a lowercase letter.
I must admit, I really know very little about string manipulation and regex in general. I'm sure there's a much more efficient and concise way of doing this, likely with string.gsub() and string.gmatch(). Your question is a day old, though, and still has no answers, so I felt that you'd appreciate the help. My drawn out example...
local str = "CatCook" local SplitLocation = string.find(str,"%l%u") --returns location of instance described. (3,4) in this example local FirstString = string.sub(str,0,SplitLocation) --get section from beginning of string to SplitLocation local SecondString = string.sub(str,SplitLocation + 1) --get section from SplitLocation to end of string local FinalString = FirstString .. " " .. SecondString print(FinalString) --prints "Cat Cook"
I hope this helps, and I highly recommend reading here for an in-depth discussion on string patterns/manipulation.