我有一个包含数字的字符串(如,
图像/cerberus5 5
期望的结果
图像/金属陶瓷4
如何从第一个字符串中的'5‘减去1以获得第二个字符串中的'4’?
发布于 2014-07-13 20:10:14
这是一个原始的例子,但是您可以这样做:
$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变得更加松散。
通过将此代码放入函数或类方法中,您可以添加一个参数,以便能够自动告诉代码添加、减去或对尾数进行其他修改。
发布于 2014-07-13 20:24:36
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 6
和
var test = subOne("images/cerberus5");将返回图像/cerberus4 4
https://stackoverflow.com/questions/24726639
复制相似问题