Regex for replacing the number by 2* the number -1. Used for replacing file names

[亡魂溺海] 提交于 2019-12-11 16:52:43

问题


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";


来源:https://stackoverflow.com/questions/5025608/regex-for-replacing-the-number-by-2-the-number-1-used-for-replacing-file-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!