Posted 20 August 2014 - 10:59 PM
Hey, guys, I'm trying to find a more elegant solution for something I've been working on.
My problem is that I'm trying to replace all occurrences of a set of characters which are consecutively placed in a string (right next to one another) with a single string.gsub call.
For example, if I have the string
I've tried
The solution that I whipped up works, but it's rather verbose and fails the single statement requirement that I wanted. None the less, here it is:
Thanks for your help!
My problem is that I'm trying to replace all occurrences of a set of characters which are consecutively placed in a string (right next to one another) with a single string.gsub call.
For example, if I have the string
ababababcbcbcbcbefefef
, I want to get rid of everything that isn't an 'ab' pair. However, when I try the following:
string.gsub ("ababababcbcbcbcbefefef", "[^ab]")
, the output removes anything that is not either an 'a' or a 'b'. So, the in the cb pairs, the 'c' is removed, but the 'b' remains although I don't want it to do so.I've tried
string.gsub ("ababababcbcbcbcbefefef", "[^(ab)]")
string.gsub ("ababababcbcbcbcbefefef", "[^a][^b]")
and some others without success.The solution that I whipped up works, but it's rather verbose and fails the single statement requirement that I wanted. None the less, here it is:
local s = "ababababcbcbcbcbefefef"
local o = s:gsub ("ab", "##"):gsub ("[^##]", ";;"):gsub ("##", "ab")
This replaces all occurrences of 'ab' with '##', replaces all occurrences of anything that isn't a '##' pair with a ';;' pair, and finally replaces all '##' pairs with the desired 'ab' pair. I'm doing this so I can use gmatch to grab as many occurrences of 'ab' as possible in a single match while maintaining their positions in the line. If anyone has a suggestion to do this without isolating the pair and then using '%w%w+', then I'd love that even more than a solution to this problem :)/>.Thanks for your help!