Math operations in regex

I need to add a number to a backreference while doing a replace operation.

e.g. I am rewriting a URL

www.site.com/doc.asp?doc=321&language=1

to

www.site.com/headline/100321.article

I'm doing a simple replace, but I need to add 100,000 to the doc ID. What I have below works so far without adding anything.

s/.*doc=(\d+).*/www.site.com\/headline\/$1.article/g;

How can I add 100,000 to $1?

Note, you can't just add 100 before the number because the doc ID might be > 999.


Solution 1:

using Perl:

s/.*doc=(\d+).*/"www.site.com\/headline\/".($1+100000).".article"/e;

as you've done with e flag, the right part becomes now an expression. so you have to wrap the non-capture part as strings.

Solution 2:

That's not possible in regex. Regex only matches patterns, it doesn't do arithmetic.

The best you can do is something verbose like:

match       replace

(\d{6,})    $1
(\d{5})     1$1
(\d{4})     10$1
(\d{3})     100$1
(\d{2})     1000$1
(\d)        10000$1

Solution 3:

If you only have a few articles you could just brute force it

...doc=322 -> www.site.com/headline/100322.article
...doc=323 -> www.site.com/headline/100323.article
...doc=324 -> www.site.com/headline/100324.article
...etc

Math in regex, you see it here first.