Insert a minus sign in every number

Solution for Insert a minus sign in every number
is Given Below:

I have some code that looks like this:


Is there a way to add a minus sign at the beginning of every number? Maybe with regular expressions?

Search and replace with captured group:

  • (d+) match numbers and capture it;
  • -1 add - before the matched number

Maybe with regular expressions?

You match, search, substitute, etc. with regular expressions, but regular expressions don’t do anything by themselves.

In this case, and supposing those two lines are the full content of the buffer, it is as simple as using a substitution:



  • The % means that the following command will be executed on every line in the buffer, see :help :range.

  • s/<pattern>/<replacement>/<flag> is the :help :substitute command.

  • d+ is our <pattern>:

    • d is an atom that means “any digit”,

    • + is a quantifier that means “one or more of the preceding atom, as many as possible”,

    • so our pattern means “one or more digits, as many as possible”.

  • -& is our <replacement>:

    • - is a literal -,
    • & is a special character that means “the whole match” in this context, so, if the whole match is 1009, then & is 1009 and -& is -1009. See :help sub-replace-special.
  • g is our <flag>, it is necessary for the substitution to work on every match on the line. See :help :s_flags.