2

I have strings like

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

which should be modified to

abcdef
abcd
abcde \foo 
abcd
abcde \foo 
  • if there is no | then do nothing
  • if nothing follows the |( or |) then delete these two characters
  • if something follows then replace |( or |) with <space>\

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.

3
  • Do you mean the position at the end of the string with if nothing follows? Commented Oct 3, 2018 at 7:56
  • Yes, then |( or |) are the last characters. If there is no |, then bar) should be unchanged Commented Oct 3, 2018 at 8:01
  • Then my solution should work. Commented Oct 3, 2018 at 8:17

1 Answer 1

1

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 \.
Sign up to request clarification or add additional context in comments.

8 Comments

Ups, I just realized that I forget something. A string like abcd|foo is also possible and should be changed to abcd \foo.
@Herbert Replace '|[()]' with '|[()]?'
@WiktorStribiżew how to replace the [[_TOC_]] in lua script? it has special characters.
@H_H Only [ is special, so %[%[_TOC_]]
@WiktorStribiżew I apply same rules for [^\%[2\%]^] string but, it doesn't work. I have tried with %[^\%%[2\%]^]. Am I missing something here? I am trying to replace in lua script. Thanks!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.