Regex – Do calculation on captured number in regex before using it in replacement

notepad++regex

Using a regex, I am able to find a bunch of numbers that I want to replace. However, I want to replace the number with another number that is calculated using the original – captured – number.

Is that possible in notepad++ using a kind of expression in the replacement-part?

Edit: Maybe a strange thought, but could the calculation be done in the search part, generating a second captured number that would effectively be the result?

Best Solution

Even if it is possible, it will almost certainly be "messy" - why not do the replacements with a simple script instead? For example..

#!/usr/bin/env ruby
f = File.new("f1.txt", File::RDWR)
contents = f.read()

contents.gsub!(/\d+/){|m|
  m.to_i + 1 # convert the current match to an integer, and add one
}

f.truncate(0) # empty the existing file
f.seek(0) # seek to the start of the file, before writing again
f.write(contents) # write modified file
f.close()

..and the output:

$ cat f1.txt
This was one: 1
This two two: 2
$ ruby replacer.rb
$ cat f1.txt
This was one: 2
This two two: 3

In reply to jeroen's comment,

I was actually interested if the possibility existed in the regular expression itself as they are so widespread

A regular expression is really just a simple pattern matching syntax. To do anything more advanced than search/replace with the matches would be up to the text-editors, but the usefulness of this is very limited, and can be achieved via scripting most editors allow (Notepad++ has a plugin system, although I've no idea how easy it is to use).

Basically, if regex/search-and-replace will not achieve what you want, I would say either use your editors scripting ability or use an external script.