3

I want -

  • variable++; then variable ++;
  • variable1 + variable2 nothing to do
  • variable1 +variable2 then variable1 + variable2
  • variable1+ variable2 then variable1 + variable2
  • variable1+variable2 then variable1 + variable2

similarly for -,*,/,>=,<=,!=,==.
And if -

  • variable1 = variable2 then nothing to do
  • variable1 =variable2 then variable1 = variable2
  • variable1= variable2 then variable1 = variable2
  • variable1=variable2 then variable1 = variable2

I try the search regex as [a-zA-Z]+([-+/*=]|>=|<=|!=|==) although it is not correct fully.

4

One way to do this would be this:

First change the infix operators:

:%s/\v(\w) ?(\+|-|\*|\/|\>\=|\<\=|!\=|\=|\=\=) ?(\w|-)/\1 \2 \3/g

N.B. This also handles the int x=-b case mentioned in the comments.

Then the postfix ++:

:%s/\v(\w)\+\+/\1 ++/g

Broken down, that first regular expression is:

  • \v: Turn on "very magic" matching.
  • (\w) ?: Find a "word character" optionally followed by a space, capturing the word character into a group.
  • (\+|-|\*|\/|\>\=|\<\=|!\=|\=|\=\=): Find any of +, -, *, /, >=, <=, !=, =, or ==, capturing it into a second group.
  • _?(\w|-): Find another optional space (represented here as an underscore so you can see it!) followed by another word character (or minus symbol), captured into the third group.

We then replace the entire match with the contents of the three groups, separated by spaces:

\1 \2 \3

For more info, see :help regexp, and specifically:

  • :help \magic
  • :help \w
  • :help \?
  • :help \|
  • :help \1
  • you can simplify the regex a bit by using [+*/=] instead of alternation.. for the postfix --> :%s/\w\zs++/ &/g – Sundeep Feb 15 '18 at 8:42
  • @Sundeep How do you specify <= in a square-bracket delimited character class? Your solution for the postfix is nicer, but I went with the above for simplicity--because it uses the same regex elements as the previous – Rich Feb 15 '18 at 9:23
  • @Rich your infix regex donesn't work for int x=-b;. You can also add Sundeep's comment's regex with description as alternation way. – temp1 Feb 15 '18 at 9:37
  • @helal: To match int x=-b, you can add in the -: :%s/\v(\w) ?(\+|\*|\/|\>\=|\<\=|!\=|\=|\=\=) ?(\w|-)/\1 \2 \3/g – Rich Feb 15 '18 at 9:46
  • 1
    @helal Untested: :%s/\v;([^ ])/; \1/g or using Sundeep's method: %s/;\ze[^ ]/; /g – Rich Feb 15 '18 at 11:04

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.