How to increment all numbers in the text that have space at least from one side?

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

vasik988

Posted 2020-02-05T01:07:46.417

Reputation: 23

Answers

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)

Toto

Posted 2020-02-05T01:07:46.417

Reputation: 7 722

Thank you! Very clear explanation. – vasik988 – 2020-02-05T10:42:56.723

@vasik988: You're welcome, glad it helps. – Toto – 2020-02-05T10:44:15.473