简体   繁体   English

使用正则表达式“ [element1] [element2]”将字符串拆分为数组

[英]Split string into array using regular expression “[element1][element2]”

I have the following string: 我有以下字符串:

var search = "[title|Asc][description|Desc]";

I'd like an array of: 我想要一系列:

[
    "title|Asc",
    "description|Desc"
]

I've tried various reg ex, but i just don't understand it enough. 我已经尝试过各种reg ex,但我只是不太了解。

var matches = search.split(/[^a-zA-Z0-9|]/);

Any chance i can have some help? 有机会我可以帮忙吗?

Use split and filter 使用splitfilter

var output = search.split(/[\[\]]+/).filter( s => s.length > 0 );

Demo 演示

 var search = "[title|Asc][description|Desc]"; var output = search.split(/[\\[\\]]+/).filter( s => s.length > 0 ); console.log(output); 

Explanation 说明

  • split by /[\\[\\]]+/ , which is a one or more occurrence of character class of [] /[\\[\\]]+/ split ,这是[]字符类的一次或多次出现

  • filter out empty items. filter掉空项目。

Remove the first and last [ , ] and then split by ][ 删除第一个和最后一个[] ,然后按][ ]分割

search.substring(1,search.length-1).split('][')

 var search = "[title|Asc][description|Desc]"; console.log(search.substring(1,search.length-1).split('][')) 

It is better to use a match instead of split to make sure we match string between [ and ] : 最好使用match而不是split来确保我们匹配[]之间的字符串:

 const regex = /\\[([^\\]]*)\\]/g; const str = `[title|Asc][description|Desc]`; let m; while ((m = regex.exec(str)) !== null) { console.log(m[1]); } 

RegEx Demo 正则演示

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

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