0

I am looking for an alternative to the C# Split where I can pass an array of strings.

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

I'm sure there is a solution using regEx but I can't seem to figure out how to construct the regular expression.

MtnManChris
  • 528
  • 5
  • 16

1 Answers1

2

First, get an escape extension method (to use the .NET term) on the RegExp prototype: https://stackoverflow.com/a/3561711/18771

Then:

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)"] 

where the filter function is the replacement for StringSplitOptions.RemoveEmptyEntries.

Community
  • 1
  • 1
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • 1
    `.filter(function (item) { return item != ""; })` can be replaced with `.filter(Boolean)`. – Wiktor Stribiżew Mar 02 '16 at 18:25
  • Yes, probably. It's rather un-obvious though. – Tomalak Mar 02 '16 at 18:26
  • I'm getting this error JavaScript runtime error: Array.prototype.map: argument is not a Function object. But that is ok, I'll just use the literal splitPattern – MtnManChris Mar 02 '16 at 18:27
  • What browser are you on? `Array.prototype.map` (etc) should be available on [any reasonably modern browser](http://kangax.github.io/compat-table/es5/#test-Array_methods); the list of supporting browsers goes down to IE9. If it is not available on your platform, consider including [Sugar.js](http://sugarjs.com/), which adds these kinds of methods. – Tomalak Mar 02 '16 at 18:29
  • 1
    @Tomalak It's not `Array.prototype.map` he's missing, it's `RegExp.escape`. –  Mar 02 '16 at 18:45
  • \*sigh\* You're right. I *literally* only have two sentences of text in my answer. – Tomalak Mar 02 '16 at 18:51
  • @MtnManChris You really have copy-pasted my code and have not read a single word of the text I wrote, haven't you? o_O – Tomalak Mar 02 '16 at 18:52
  • @Tomalak. Wrong, The question was how to construct the regEx expression. You supplied that with this "result: /\*|\/|\+|\-|<|>|=|<>|<=|>=|&&|\|\|/". Although @ torazaburo decided my English wasn't sufficient and did correctly point out that RegExp.escape was what was missing. – MtnManChris Mar 02 '16 at 19:48
  • @MtnManChris So what does the first sentence of my answer say? You still did not read it. – Tomalak Mar 02 '16 at 19:54