2016-03-02 67 views
0

我正在寻找替代的C#拆分,我可以传递一个字符串数组。JavaScript的请求表达式

string[] m_allOps = { "*", "/", "+", "-", "<", ">", "=", "<>", "<=", ">=", "&&", "||" }; 
string s = "@ans = .707 * sin(@angle)"; 
string[] tt = s.Split(m_allOps,StringSplitOptions.RemoveEmptyEntries);  // obtain sub string for everything in the equation that is not an operator 

我敢肯定,有一个使用regEx的解决方案,但我似乎无法弄清楚如何构造正则表达式。

+0

你想要输出什么? –

+0

@ ans,.707,sin(@angle) – MtnManChris

+0

请参阅[此演示](https://jsfiddle.net/xtsoLpvd/) –

回答

2

首先,在正则表达式原型得到一个escape扩展方法(使用.NET术语):https://stackoverflow.com/a/3561711/18771

然后:

var m_allOps = ["*", "/", "+", "-", "<", ">", "=", "<>", "<=", ">=", "&&", "||"]; 
var splitPattern = new RegExp(m_allOps.map(RegExp.escape).join('|')); 
// result: /\*|\/|\+|\-|<|>|=|<>|<=|>=|&&|\|\|/ 

var s = "@ans = .707 * sin(@angle)"; 
var tt = s.split(splitPattern).filter(function (item) { 
    return item != ""; 
}); 
// result: ["@ans ", " .707 ", " sin(@angle)"] 

其中滤波器功能是替代StringSplitOptions.RemoveEmptyEntries

+1

'.filter(function(item){ return item!=“” ; })''可以用'.filter(布尔)'代替。 –

+0

是的,可能。这是相当不明显的,但。 – Tomalak

+0

我得到这个错误的JavaScript运行时错误:Array.prototype.map:参数不是一个函数对象。但是,没关系,我只是使用文字splitPattern – MtnManChris