简体   繁体   English

在javascript中使用REGEX分割字符串

[英]Split stings using REGEX in javascript

I'm trying to parse string into 5 parts. 我正在尝试将字符串解析为5部分。 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 ? 解析单词asdf-finalizers-test/1的正确正则表达式是什么? I tried these but failed. 我尝试了这些但是失败了。

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

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' ]

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' ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM