我有一个特定的字符串,如下所示
*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 ::: |
我想提取圆括号()内的数字并计算所有这些数字的总和。 我已经尝试了以下RegEx来提取数字,但它没有返回任何结果。
str.match(/\((\d+)\)/)
答案 0 :(得分:2)
你可以试试这个:
/\((\d*\.?\d*)\)/g
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);
&#13;
在接受的答案中填写您的评论
如果我只计算括号的总和,那还有一件事 在:; :(包括:;: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);
&#13;
答案 1 :(得分:2)
您没有结果的主要原因是您没有考虑数字中的点,因此您会错过所有非整数数字。一旦你纠正了这个,你仍然只得到一个结果,因为你没有在正则表达式中指定全局修饰符(g
)。
您可以使用此三步转换:
const sum = s.match(/\([\d.]+(?=\))/g) // get the numbers
.map( a => +a.substr(1) ) // remove opening parenthesis and convert to number
.reduce( (a,b) => a+b ); // total them
演示:
const s = `*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 ::: |`;
const sum = s.match(/\([\d.]+(?=\))/g) // get the numbers
.map( a => +a.substr(1) ) // remove opening parenthesis and convert to number
.reduce( (a,b) => a+b ); // total them
console.log(sum.toFixed(2));
&#13;
注意:对.toFixed
的调用是可选的,但它解决了floating point inaccuracies可能遇到的问题。