简体   繁体   English

对两个捕获组求和

[英]Sum two capture groups

I need get two values from a string and sum them. 我需要从字符串中获取两个值并将它们相加。

var text = 'SOC 01 672 1.653.806,08 18.512,98 1.667.621,57 2.647,38 07 23 12.965,11 0,00 12.965,11 0,00 13 5 10.517,81 0,00 10.517,81 0,00';
var reg  = new RegExp('SOC 01' +  '\\b.*?(?:\\d\\S*\\s+){3}(\\d\\S*)', 'i');
var reg2 = new RegExp('SOC 01' +  '\\b.*?(?:\\d\\S*\\s+){7}(\\d\\S*)', 'i');
var match = reg.exec(text);
var match2 = reg2.exec(text);

Output: 输出:

match[1] -> '1.667.621.57'
match2[1] -> '12.965.11'

(OBS: If you try run in the console the last number will have a comma, but in my node.js environment is a dot.) (OBS:如果尝试在控制台中运行,则最后一个数字将带有逗号,但是在我的node.js环境中是一个点。)

I would like to know if i can create just one regex with two groups and sum them together. 我想知道我是否只能创建一个带有两个组的正则表达式并将它们加在一起。

The total should be 1.691.104,49 总数应为1.691.104,49

I was trying to sum like this: 我试图像这样总结:

(+match[1]) + (+match2[1])

output: NaN

Thanks. 谢谢。

You're going to have to do something like: 您将必须执行以下操作:

Number(match[1].replace(/[\.,]/g, ''))

To strip out the . 剥去. s and , s before summing the numbers. s和, s,然后将数字相加。

If you need to get the number back into the same format, you can do something like this: 如果您需要将号码恢复为相同的格式,则可以执行以下操作:

var total = Number(match[1].replace(/[\.,]/g, '')) + Number(match2[1].replace(/[\.,]/g, ''));

var result = String(total);
result = result.replace(/(?=\d{2}$)/, ',');
result = result.replace(/\B(?=(\d{3})+(?!\d))/g, '.');

Which produces 1.680.586,68 . 产生1.680.586,68 I have the same question as stribizhev about how you are doing the summing. 关于您如何进行求和,我和stribizhev有相同的问题。

Here is the fiddle for the above example: https://jsfiddle.net/qw700fq9/ 这是上面示例的小提琴: https : //jsfiddle.net/qw700fq9/

Here is the updated fiddle - cleaned it up a bit: https://jsfiddle.net/rdu15ds3/ 这是更新的小提琴 -对其进行了一些清理: https : //jsfiddle.net/rdu15ds3/

Also, adding the decimals back in was based on the answers to this question: How to print a number with commas as thousands separators in JavaScript 另外,重新添加小数位数是基于以下问题的答案: 如何在JavaScript中以逗号分隔的数字打印数字作为千位分隔符

The regex is returning a string. 正则表达式返回一个字符串。 You need to convert them to numbers before adding them. 您需要先将它们转换为数字,然后再添加它们。

function toNumber(n){
    return parseFloat(n.replace(/./g,'').replace.(/,/g,'.'));
}

toNumber(+match[1]) + toNumber(+match2[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM