tags:

views:

74

answers:

3

hi everybody... I need a javascript code that split a string like below:

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

Output:

a=>aa

b=>b||b 

c=>cc

I'd written different codes like:

split(/ \ | /)

or

split(/ \| (?! \ |) /)

but didn't work.

please help me...

I really need it fast.

+3  A: 

Split with /\|(?=\s)/ for your case

"a=>aa| b=>b||b | c=>cc".split(/\|(?=\s)/)
# a=>aa
# b=>b||b 
# c=>cc
S.Mark
Note: my answer only works for OP's example. please take a look Kobi's [answer](http://stackoverflow.com/questions/2719300/write-an-expression-in-javascript/2719388#2719388), thats more appropriate one actually.
S.Mark
A: 

I tested the first answer and it did not work as I believe you intended:

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

unfortunately the answer that I came up with isn't much better just add a space after the pipe marker in your regex. Also answer by @S.Mark is valid, tested.

Gabriel
+1  A: 

This confusing looking regex will work without spaces around the pipes:

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

Instead of splitting, it searches for tokens with double pipes, but not single. If you have spaces and need to match b=>b|b | c=>5 use S.Mark's regex, but this can help in other cases.
To clarify, [^|]|\|\| reads [not a pipe] OR [two pipes].

Kobi
+1, yours is more appropriate than mine.
S.Mark
Thanks. That depends on the context though, if the OP has tokens with single pipes (which is very possible), your version will work better.
Kobi