gpt4 book ai didi

javascript - 计算字符串中括号内的数字

转载 作者:行者123 更新时间:2023-11-28 14:59:29 24 4
gpt4 key购买 nike

我有一个如下所示的特定字符串

*WTY:   but the light of the dining room suddenly turn off .
%mor: conj|but det|the n|light prep|of det|the adj|dining n|room adv|suddenly v|turn adv|off .
%snd: <00:14:74><00:25:53>
%WTY: {and} rpl but {suddenly} rpl (0.43) {the} * (1.07) {the light (0.78) suddenly turn off and} # (1.24) the light of the dining room suddenly turn off . err_m_s err_m_l ::: |

我想提取圆括号 () 内的数字并计算所有这些数字的总和。我已尝试使用以下正则表达式来提取数字,但它没有返回任何结果。

str.match(/\((\d+)\)/)

最佳答案

你可以试试这个:

/\((\d*\.?\d*)\)/g

Explanation

const regex = /\((\d*\.?\d*)\)/g;
const str = `*WTY: but the light of the dining room suddenly turn off .
%mor: conj|but det|the n|light prep|of det|the adj|dining n|room adv|suddenly v|turn adv|off .
%snd: <00:14:74><00:25:53>
%WTY: {and} rpl but {suddenly} rpl (0.43) {the} * (1.07) {the light (0.78) suddenly turn off and} # (1.24) the light of the dining room suddenly turn off . err_m_s err_m_l ::: |`;
let m;

var val=0.0;
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
//console.log(m[1]);
val+=parseFloat(m[1]);
}
console.log(val);

在已接受的答案中涵盖您的评论

Just one more thing what if I have to only count the sum of brackets right before or after the :;: (including :;:a, :;:b, :;:a) .

您可以应用此正则表达式:

:;:\s*\((\d*\.?\d*)\)|\((\d*\.?\d*)\)\s*:;:

const regex = /:;:\s*\((\d*\.?\d*)\)|\((\d*\.?\d*)\)\s*:;:/g;
const str = `*WTY: but the light of the dining room suddenly turn off .
%mor: conj|but det|the n|light prep|of det|the adj|dining n|room adv|suddenly v|turn adv|off .
%snd: <00:14:74><00:25:53>
%WTY: {and} rpl but {suddenly} rpl :;: (0.43) {the} * (1.07) :;: {the light (0.78) suddenly turn off and} # (1.24) the light of the dining room suddenly turn off . err_m_s err_m_l ::: |`;
let m;

var val=0.0;
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if(typeof m[1] !== 'undefined')
val+=parseFloat(m[1]);
else
val+=parseFloat(m[2]);
//val+=parseFloat(m[1]);
}
console.log(val);

关于javascript - 计算字符串中括号内的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41660778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com