嵌套括号一一对应地得到字符串 [英] Nested parentheses get string one by one
本文介绍了嵌套括号一一对应地得到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有文本框,用户编写了一个公式,我从文本框中获取了用于拆分括号的文本.通过这种方式,我不尝试计算公式,而是尝试获取字符串.我试图从嵌套获取字符串括号这是我的代码:
I have textbox and user write a formula and I get the text from textbox to split the parentheses .By the way I'm not trying to calculate formula I try to just get strings .I'm trying to get strings from nested parentheses Here is my code:
var txt = "((a-b)/month)/(c+d)";
var reg = /^\((.+)\)$/;
var newTxt = txt.split('(');
for (var i = 1; i < newTxt.length; i++) {
var value = newTxt[i].split(')')[0];
if (value == "") {
value = txt.match(reg)[1];
}
console.log(value);
}
我的输出是
(a-b)/month)/(c+d
a-b
c+d
但是我试图在像
(a-b)/month
a-b
c+d
推荐答案
这是另一种方式
var a = [], r = [];
var txt = "(((a-b)+(f-g))/month)/(c+d)";
for(var i=0; i < txt.length; i++){
if(txt.charAt(i) == '('){
a.push(i);
}
if(txt.charAt(i) == ')'){
r.push(txt.substring(a.pop()+1,i));
}
}
alert(r);
这篇关于嵌套括号一一对应地得到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文