1

I want to increment numbers which are written like this: add(1 ) or add( 1), but not like this add(1). I have one code that works in Notepad++ with Python Script plugin but it increments all numbers:

import re

def calculate(match):
    return '%s' % (str(int(match.group(1)) + 1))

editor.rereplace('(\d+)', calculate)

Also, would be very good to know how to increment numbers in only add(1 ), only add( 1), only add(1) cases. You can suggest me any software, not particularly Notepad++.

| |
2

Change the script into:

import re
import random
def calculate(match):
    return '%s' % (str(int(match.group(1)) + 1))

editor.rereplace('((?<=add\( )\d+(?=\))|(?<=add\()\d+(?= \)))', calculate)

Regex explanation:

(                   # group 1
    (?<=add\( )     # positive lookbehind, make sure we have "add( " (with a space after parenthesis) before
    \d+             # 1 or more digits
    (?=\))          # positive lookahead, make sure we have a closing parenthesis after
  |               # OR
    (?<=add\()      # positive lookbehind, make sure we have "add(" (without spaces after parenthesis) before
    \d+             # 1 or more digits
    (?= \))         # positive lookahead, make sure we have a space and a closing parenthesis after
)                   # end group 1

With an input like:

add(1 ) or add( 1), but not like this add(1)

it will give:

add(2 ) or add( 2), but not like this add(1)
| |
  • Thank you! Very clear explanation. – vasik988 Feb 5 at 10:42
  • @vasik988: You're welcome, glad it helps. – Toto Feb 5 at 10:44

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.