views:

92

answers:

4

I'd asked a question about the splitting the a string like below:

Input string: a=>aa| b=>b||b | c=>cc

and the output:

a=>aa
b=>b||b 
c=>cc

Kobi's answer was:

var matches = "a=>aa|b=>b||b|c=>cc".match(/(?:[^|]|\|\|)+/g)

His answer worked, but I need to use the .split() method and store the outputs in an array.

So I can't use the .match() Method.

How can I do it?

+1  A: 

.match return array too, so there is no problem using .match

arr = "a=>aa|b=>b||b|c=>cc".match(/(?:[^|]|\|\|)+/g)
// a=>aa,b=>b||b,c=>cc
arr.length
// 3
arr[0]
// a=>aa
S.Mark
actually I need this question for my complier course.I explained the match function to my professor and he said that you must answer this question with split...One more thing: the input is : a=>aa|b=>b||b|c=>cc (there is no space between each character)
Hero
+2  A: 

Here's my stab:

var str = 'a=>aa| b=>b||b | c=>cc';
var arr = str.split(/\s*\|\s+/);
console.log(arr)
// ["a=>aa", "b=>b||b", "c=>cc"]

var obj = {}; // if we want the "object format"
for (var i=0; i<arr.length; i++) {
  str=arr[i];
  var match = str.match(/^(\w+)=>(.*)$/);

  if (match) { obj[match[1]] = match[2]; }
}
console.log(obj);

// Object { a:"aa", b:"b||b", c: "cc" }

And the RegExp:

/
 \s*   # Match Zero or more whitespace
 \|    # Match '|'
 \s+   # Match one or more whitespace (to avoid the ||)
/
gnarf
+1  A: 

While I hate arguing with myself, another possible solution is:

var matches = 'a=>aa|b=>b||b|c=>cc'.split(/\b\s*\|\s*\b/g);

Meaning: split when you see | surrounded by spaces, and between alphanumeric characters.
This version will also leaves d|=d intact.
\b can introduce errors though, it might will not split if the pipe isn't between alphanumeric characters, for example a=>(a+a)|b=>b will not split.

Kobi
A: 

I posted this in your other copy of this question (please don't ask a question multiple times!)

This ought to do it:

"a=>aa|b=>b||b|c=>cc".split(/\|(?=\w=>)/);

which yields:

["a=>aa", "b=>b||b", "c=>cc"]
icio