正则表达式在方括号内得到两个特定字符

时间:2022-12-01 21:43:09

Not too well-versed with Regex. I have a string like this:

不太熟悉正则表达式。我有一个像这样的字符串:

 var str = "WOMEN~~Accessories >Underwear~~Socks, Tights & Leggings"

Using Javascript, I want to split at: ~~, &, > and , including potential white space surrounding them.

使用Javascript,我想分成:~~,&,>,并包括它们周围的潜在空白区域。

So far I've got:

到目前为止,我有:

 var arr = str.split(/[\s>&,]/g);
 for (var i = 0; i<arr.length; i++){
    if(arr[i]){accepted.push(arr[i])}
 }

This doesn't account for multiple characters though (and I'm sure there's a better way to regex in the white space rather than a for loop after the fact!) and the ~~ isn't selected.

这虽然不考虑多个字符(我确信在白色空间中有更好的正则表达方式,而不是事后的for循环!)并且没有选择~~。

I'm thinking something along the lines of /[\s>&,[~~]]/g but this doesn't work. How can I do this with regex?

我正在考虑/ [\ s>&,[~~]] / g的内容,但这不起作用。我怎么能用正则表达式做到这一点?

2 个解决方案

#1


1  

Try this:

/\s*[\s>&,\[\]~]+\s*/g

Description

正则表达式在方括号内得到两个特定字符

Demo

http://jsfiddle.net/p7FFD/

#2


0  

var arr = str.split(/(~~|[\s>&,]+)/g);

So you're splitting on either ~~ or any combination of whitespace, ampersands, greater than (>) and commas.

所以你要分裂~~或空白,&符号,大于(>)和逗号的任何组合。

#1


1  

Try this:

/\s*[\s>&,\[\]~]+\s*/g

Description

正则表达式在方括号内得到两个特定字符

Demo

http://jsfiddle.net/p7FFD/

#2


0  

var arr = str.split(/(~~|[\s>&,]+)/g);

So you're splitting on either ~~ or any combination of whitespace, ampersands, greater than (>) and commas.

所以你要分裂~~或空白,&符号,大于(>)和逗号的任何组合。