regexsearchreplacevisual-studio-codeincrement

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 :)


Solution

  • 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:

    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)).