Regex for replacing the number by 2* the number -1

2019-09-17 01:38发布

问题:

I need the regular expression for multiplying the digits in the filename by 2 and subtracting 1. for eg: filename12.pdf should become filename23.pdf filename225.pdf should become filename449.pdf

Please help me with the regular expression.

回答1:

A regex generally cannot do calculations, but it can help you capture the number. You can use a callback of replace. Here's C#, for example:

Helper method (we could have used a lambda, but it's less pretty):

public string CalculateNumber(Match match)
{
    int i = Convert.ToInt32(match.Value);
    i = i * 2 - 1;
    return i.ToString();
}

Regex replace:

String fileName = "filename23.pdf";
fileName = Regex.Replace(fileName, @"\d+", CalculateNumber);

An important note here is that the string may represent a too large integer (so it won't parse). Also, i*2-1 may overflow, resulting in a negative number. You may use a checked block, or use a BigInteger (with .Net 4).



回答2:

Here is a way to do it in Perl:

#!/usr/bin/perl
use 5.10.1;
use strict;
use warnings;

my $in = 'filename225.pdf';
$in =~ s/(\d+)/$1*2-1/e;
say $in;

output:

filename449.pdf

or in php :

function compute($matches) {
    return $matches[1]*2-1;
}
$in = 'filename225.pdf';
$res = preg_replace_callback('/(\d+)/',"compute", $in);;
echo $res,"\n";


标签: regex digit