jeroen
jeroen

Reputation: 91792

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

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?

Upvotes: 3

Views: 7383

Answers (4)

Eric Wendelin
Eric Wendelin

Reputation: 44379

Hmmm... I'd have to recommend AWK to do this.

http://en.wikipedia.org/wiki/AWK

Upvotes: 2

dbr
dbr

Reputation: 169693

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.

Upvotes: 3

Andrew Redd
Andrew Redd

Reputation: 4692

notepad++ has limited regular expressions built in. There are extensions that add a bit more to the regular expression find and replace, but I've found those hard to use. I would recommend writing a little external program to do it for you. Either Ruby, Perl or Python would be great for it. If you know those languages. I use Ruby and have had lots of success with it.

Upvotes: 1

John Feminella
John Feminella

Reputation: 311735

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

Interpolated evaluation of regular-expression matches is a relatively advanced feature that I probably would not expect to find in a general-purpose text editing application. I played around with Notepad++ a bit but was unable to get this to work, nor could I find anything in the documentation that suggests this is possible.

Upvotes: 3

Related Questions