2016-03-02 68 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