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

标签 javascript regex

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

*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/

相关文章:

javascript - 如何在其他两个字符串之间获取多个字符串

javascript - 与基础版本 SES 相比,SESv2 的 aws-sdk 是否缺少某些功能?

javascript - 来自 Firefox 附加组件的内容脚本不会写入 IndexedDB

regex - 正则表达式除最后一个字符外的所有字符

javascript - 针对 `undefined` 进行测试时,RegExp 给出了意外结果

python - 从 Pandas 列中删除字符

带有回调的两个函数之间的javascript变量范围问题

javascript - phonegap 离线/在线事件不工作

java - 检查字符串是否包含数值和字母值

Javascript 正则表达式 - 多行