javascript reqular表达式

时间:2016-03-02 18:13:12

标签: javascript regex split

我正在寻找C#Split的替代品,我可以传递一个字符串数组。

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的解决方案,但我似乎无法弄清楚如何构建正则表达式。

1 个答案:

答案 0 :(得分:2)

首先,在RegExp原型上获取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