如何从字符串中包含的数字中减去


How to subtract from a number contained in a string?

我有一个包含数字的字符串,例如

图像/cerberus5

期望的结果

图像/cerberus4

我如何从第一个字符串中的'5'减去1以获得第二个字符串中的'4' ?

这是一个原始示例,但您可以这样做:

$old_var = 'images/cerberus4';
$matches = [];
$success = preg_match_all('/^([^'d]+)('d+)$/', $old_var, $matches);
$new_val = '';
if (isset($matches[2]) && $success) {
    $new_val = $matches[2][0].((int)$matches[2][0] + 1);
}

这并不意味着完美的解决方案,但只是给一个可能的选择方向。

RegEx没有检测到的(因为它更严格)是,如果没有尾随数字(如images/cerberus),它将无法工作,但由于它似乎是一个"预期的"模式,我也不会允许RegEx更宽松。

通过将此代码放入函数或类方法中,您可以添加一个参数,以便能够自动告诉代码对末尾的数字进行添加、减去或其他修改。

function addOne(string){
    //- Get first digit and then store it as a variable
    var num = string.match(/'d+/)[0];
    //- Return the string after removing the digits and append the incremented ones on the end
    return (string.replace(/'d+/g,'')) + (++num);
}
function subOne(string){
    var num = string.match(/'d+/)[0];
    //- Same here just decrementing it
    return (string.replace(/'d+/g,'')) + (--num);
}

不知道这是否足够好,但这只是两个返回字符串的函数。如果这必须通过JavaScript完成,那么执行:

var test = addOne("images/cerberus5");

将返回图像/cerberus6

var test = subOne("images/cerberus5");

将返回images/cerberus4