Ian Boyd
Ian Boyd

Reputation: 256581

String Replace in Lua

i am looking to write a function in Lua that replaces all occurrences of one string with another, e.g.:

function string.replace(s, oldValue, newValue)
   return string.gsub(s, oldValue, newValue);
end;

What i need (unless Lua already has a string replace function) is a function to escape Lua regular expressionpattern strings (unless Lua already has an EscapeRegularExpressionPattern function)

i've tried to start writing the proper string.replace function:

local function EscapeRegularExpression(pattern)
    -- "." ==> "%."
    local s = string.gsub(pattern, "%." "%%%.");

    return s;
end;

function string.replace(s, oldValue, newValue)
    oldValue = EscapeRegularExpression(oldValue);
    newValue = EscapeRegularExpression(newValue);

    return string.gsub(s, oldValue, newValue);
end;

But i cannot easily think of all the Lua regular expressionpattern keywords that need to be escaped.

Bonus Example

Another example that needs a fix might be:

//Remove any locale thousands separator:
s = string.gsub(s, Locale.Thousand, "");

//Replace any locale decimal marks with a period
s = string.gsub(s, Locale.Decimal, "%.");

Upvotes: 2

Views: 16257

Answers (2)

Jane T
Jane T

Reputation: 2091

I use

-- Inhibit Regular Expression magic characters ^$()%.[]*+-?)
function strPlainText(strText)
    -- Prefix every non-alphanumeric character (%W) with a % escape character, 
    -- where %% is the % escape, and %1 is original character
    return strText:gsub("(%W)","%%%1")
end -- function strPlainText

Upvotes: 3

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

Check out documentation on patterns (that's section 5.4.1 for Lua 5.1), most interesting would be list of magic characters:

x: (where x is not one of the magic characters ^$()%.[]*+-?) represents the character x itself.

Escape them with preceding % before using string in gsub and you're done.

To be extra sure you can set up a while loop with string.find that have convenient "plain" flag and string.sub necessary parts of string manually.

Upvotes: 1

Related Questions