lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


David Given wrote:
One thing I find myself needing to do suprisingly frequently is to replace all
occurances of a particular substring with a different substring, in a larger
string.

Aha, you cry. string.gsub() is exactly what I'm looking for... except it's
not, because I can't turn off regular expression processing, and my pattern is
algorithmically generated and might contain '%' characters.

What's the best way around this? What I'd *like* is for a 'plain' parameter to
be added to string.gsub(), but of course that's unlikely to happen.

Although I believe it has been already asked...

So far
I've been using a fairly naive approach --- repeatedly calling string.find,
constructing a list of fragments, and then concatenating them with
table.concat. It's a bit verbose and quite irritating, and I'm not convinced
about the speed. Are there any more cunning ways of doing this?

Perhaps that:

oldString = "Sale: 10% off, plus additional 5% off if 100% insured"
generatedPattern = "0%"
replace = "$"
pattern = string.gsub(generatedPattern, "%%", "%%%%")
newString = string.gsub(oldString, pattern, replace)
print(newString)

Seems to work, at least with this simplistic test...

--
Philippe Lhoste
--  (near) Paris -- France
--  http://Phi.Lho.free.fr
--  --  --  --  --  --  --  --  --  --  --  --  --  --