12
Test 300
Test 301
Test 302

I can use regex find to loop through these:

Test (3[0-9]*)

When I try replace with math it concatenates instead of evaluates?

Test $1-100

So, it becomes:

Test 300-100

Is it possible to evaluate instead of concatenate, so it becomes:

Test 200

Thanks.

8
  • 1
    The match $1 is a string, to perform mathematical operations you need to cast them to Number.
    – Tushar
    Feb 9, 2016 at 3:17
  • 2
    It is not possible in any regex flavor. Feb 9, 2016 at 7:22
  • 1
    it works in vim regex: %s@{fileID: (213[0-9]*)@\='{fileID: '.(submatch(1)-1900)@
    – Rakka Rage
    Feb 9, 2016 at 14:32
  • %s@Test (3[0-9]*)@\='Test '.(submatch(1)-100)@
    – Rakka Rage
    Feb 9, 2016 at 15:54

2 Answers 2

8

You can use the VS Code Super Replace extension to achieve this.

Find field is the regular expression

Replace is the replace expression. Sub match with $$index syntax will be resolved using the function in Processing function field

Here is an example of use that answers your question :

Super Replace VS Code demo

1

There are more extensions that can do this now, including one I wrote Find and Transform.

With this keybinding:

{
  "key": "alt+m",                     // whatever keybinding you want
  "command": "findInCurrentFile",
  "args": {
    "find": "(?<=Test\\s)(3\\d\\d)",  // get 300+ in capture group 1
    "replace": "$${ return $1 - 100 }",      // subtract 100 from capture group 1
    "isRegex": true
  }
}

evaluate math on a capture group

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.