0

I'm trying to parse string into 5 parts. For example:

var str1 = '#<SYSTEM list-of / asdf-finalizers-20140826-git / quicklisp 2014-08-26>'

// filter is used to remove empty strings from the returned array
str1.split(/[ #<>/]/).filter(function(n) { return n !== ''; });

// str1[0] -> SYSTEM
// str1[1] -> list-of
// str1[2] -> asdf-finalizers-20140826-git
// str2[3] -> quicklisp
// str2[3] -> 2014-08-26


But the problem is, I can't parse the strings containing slash in the middle of words For example,

#<SYSTEM asdf-finalizers-test/1 / asdf-finalizers-20140826-git / quicklisp 2014-08-26>

What is the correct regex to parse the word asdf-finalizers-test/1? I tried these but failed.

/[(\s\/\s) #<>]/, /[(?:\s\/\s) #<>]/, /[ #<>]|(\s\/\s)/

3
  • 1
    If slashes must have spaces on either side to function as separators, then use /[ #<>]| \/ ]/. Your filter can also be written as filter(Boolean). Commented Sep 11, 2014 at 9:43
  • @torazaburo Thanks. filter(Boolean) is so handy. But /[ #<>]| \/ ]/ doesn't work. I'm using node.js 0.10.31 It is because of nodejs? Commented Sep 11, 2014 at 9:49
  • 1
    Swap the two options, so / \/ |[ #<>]/. Works in both browser and node. The problem is that if the ` / ` option is placed second, it matches on the space first before it gets to the second option, and you end up with slashes in your output. Commented Sep 11, 2014 at 9:55

2 Answers 2

2

The following seems to work:

/ \/ |[ #<>]/

'#<SYSTEM asdf-finalizers-test/1 / asdf-finalizers-20140826-git / quicklisp 2014-08-26>'.split(/ \/ |[ #<>]/).filter(Boolean)
> [ 'SYSTEM',
    'asdf-finalizers-test/1',
    'asdf-finalizers-20140826-git',
    'quicklisp',
    '2014-08-26' ]
Sign up to request clarification or add additional context in comments.

Comments

1

You could use a negative lookahead to not to split according to / when it is followed by a word character.

> var s = "#<SYSTEM asdf-finalizers-test/1 / asdf-finalizers-20140826-git / quicklisp 2014-08-26>"
> s.split(/[ #<>]|\/(?!\w)/).filter(function(n) { return n !== ''; });
[ 'SYSTEM',
  'asdf-finalizers-test/1',
  'asdf-finalizers-20140826-git',
  'quicklisp',
  '2014-08-26' ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.