0

I have a document containing these types of strings:

C(A,B)

C(D,E)

C(D,
E)

I am trying to replace every occurence of C(...) with \SC{...}, changing the C in front of the bracket and the brackets themselves. The brackets can span multiple lines. How can this be done?

Edit: The document contained other types of brackets as well. They should not be replaced.

My idea would be to iterate through occurences, and use the method described here to replace the brackets.

  • Do you have any parenthesis that should not be changed to brackets? Then you could simply do several simple substitute commands. – DJMcMayhem Nov 3 '16 at 5:55
  • @DJMcMayhem I do have brackets that I do not want to change. – Henricus V. Nov 3 '16 at 6:04
  • 2
    What did you try? – romainl Nov 3 '16 at 6:25
  • Can you have embedded parenthesis like: C(A(f), Z())? Is no, a simple :substitute can do it thanks to \_.\{-} that'll match as few things as possible on multiple lines. Otherwise, you'll need to search for C( and apply the old trick with % and ````` – Luc Hermitte Nov 3 '16 at 7:29
  • @romainl See the updated question. – Henricus V. Nov 3 '16 at 13:35
3

Based on the wording of your question, it seems like I can assume that A, B, D, and E are not expressions that themselves contain parantheses. Based on the comments, it might not be assumed. I therefore provide two answer.


If there are not nested parantheses, then the following regular expression should work:

:%s/C(\(\_[^)]\+\))/\\SC{\1}/g

Here \_ allows the following atom to match across line boundaries, see :h \_.


If there are nested parantheses, the substitution becomes very hard to do with a regular expression (at least in general). In this case, I would rather use a macro:

  1. Put the cursor on a C, then start recording with qa.
  2. Do: s\SC<esc> to replace C with \SC.
  3. Do: l%r} to replace the last ) with }.
  4. Do: <c-o>r{ to replace the first ( with {.
  5. Search for next occurance: /C(
  6. Stop recording: q.

Now you may repeat the substitution with @a and then @@ for the consecutive occurances.

Note: Here <esc> is the literal escape character and <c-o> is Ctrl+o.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.