Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search and replace with regex to increment numbers in Visual Studio Code

I'm currently working on a big svg sprite. The diffrent images are always 2000px apart.

What I have is:

<g transform="translate(0,0)">
<g transform="translate(0,2000)">
<g transform="translate(0,4000)">

After regex want this so just adding 2000 onto the second number:

<g transform="translate(0,2000)">
<g transform="translate(0,4000)">
<g transform="translate(0,6000)">

I have the issue now that some new images have to be put at the top of the document, thus meaning i would need to change all numbers and they are quite alot.

I was thinking about using regular expressions and even found out that it works in the search bar of VS Code. The thing is i never worked with any regex and i'm kinda confused.

Could someone give me a solution and an explanation for incrementing all the sample numbers by 2000? I hope i understand it afterwards so i can get my foot into that topic. I'm also happy with just links to tutorials in general or my specific use case.

Thank you very much :)

like image 635
Blue Lovag Avatar asked Oct 15 '19 10:10

Blue Lovag


1 Answers

In VSCode, you can't replace with an incremented value inside a match/capture. You can only do that inside a callback function passed as the replacement argument to a regex replace function/method.

You may use Notepad++ to perform these replacements after installing Python Script plugin. Follow these instructions and then use the following Python code:

def increment_after_openparen(match):
    return "{0}{1}".format(match.group(1),str(int(match.group(2))+2000))

editor.rereplace(r'(transform="translate\(\d+,\s*)(\d+)', increment_after_openparen)

See the regex demo.

Note:

  • (transform="translate\(\d+,\s*)(\d+) matches and captures into Group 1 transform="translate( + 1 or more digits, then , and 0 or more whitespaces (with (transform="translate\(\d+,\s*))) and then captures into Group 2 any one or more digits (with (\d+))
  • match.group(1) is the Group 1 contents, match.group(2) is the Group 2 contents.

Basically, any group is formed with a pair of unescaped parentheses and the group count starts with 1. So, if you use a pattern like (Item:\s*)(\d+)([.;]), you will need to use return "{0}{1}{2}".format(match.group(1),str(int(match.group(2))+2000), match.group(3)). Or, return "{}{}{}".format(match.group(1),str(int(match.group(2))+2000), match.group(3)).

like image 124
Wiktor Stribiżew Avatar answered Sep 20 '22 15:09

Wiktor Stribiżew