Red-Cloud
Red-Cloud

Reputation: 458

Lua: Replace characters in a string

I have strings like

abcdef
abcd|(
abcde|(foo 
abcd|)
abcde|)foo

which should be modified to

abcdef
abcd
abcde \foo 
abcd
abcde \foo 

I am interested in short pattern expressions, if possible. I can do this by several string.find and string.sub but then I have a lot of if statements.

Upvotes: 2

Views: 5297

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

You may use

function repl(v)
    res, _ = string.gsub(v:gsub('|[()]$', ''), '|[()]', ' \\')
    return res
end

See Lua demo online

Details

  • '|[()]$' matches | and then either ( or ) at the end of the string, and string.gsub replaces these occurrences with an empty string
  • |[()] then matches | and then either ( or ) anywhere in the string, and string.gsub replaces these occurrences with a space and \.

Upvotes: 1

Related Questions