[英]How to split string into multiple substrings enclosed with [ ] and where delimiter is also found within the substring?
TLDR; TLDR;
In Javascript, how do I split this string [test,string,0,5,bob,0,1],[age,number,1,100,20,0,1], [male,const,0,0,yes,200,1]
into an array of substrings each bounded by []
: 在Javascript中,如何分割此字符串[test,string,0,5,bob,0,1],[age,number,1,100,20,0,1], [male,const,0,0,yes,200,1]
放入由[]
[test,string,0,5,bob,0,1],[age,number,1,100,20,0,1], [male,const,0,0,yes,200,1]
的子字符串数组:
[test,string,0,5,bob,0,1]
, [age,number,1,100,20,0,1]
, [male,const,0,0,yes,200,1]
[test,string,0,5,bob,0,1]
, [age,number,1,100,20,0,1]
, [male,const,0,0,yes,200,1]
Context: 内容:
I need to process lines from a config file into an array, using Node JS. 我需要使用Node JS将配置文件中的行处理到数组中。 A line is a string of the form: 行是以下形式的字符串:
someID,[test,string,0,5,bob,0,1],[age,number,1,100,20,0,1],[male,const,0,0,yes,200,1]
This needs to end up as an element in an array: 这需要最终作为数组中的元素:
var config = [
// One line from the config file:
['someID', ['test','string',0,5,'bob',0,1],[12,'number',1,100,20,0,1],['male','const',0,0,'yes',200,1]],
// more elements each representing a line...
];
I can get the first item off the config line, 'someID' above, using line.split(',',1)[0]
but how do I separate the rest of the string into sub elements bound by [
and ]
? 我可以使用line.split(',',1)[0]
从配置行中获取第一项,上面的“ someID”,但是如何将字符串的其余部分分成由[
和]
绑定的子元素?
I've tried JS string.match() : 我试过JS string.match():
var elements = str.match(/\[(.*)\]/g);
but I get a single string with 但我得到一个字符串
"[test,string,0,5,bob,0,1],[age,number,1,100,20,0,1], [male,const,0,0,yes,200,1]"
(I realise this is because it's only matching against the first [
and last ]
and not processing everything in between) (我意识到这是因为它仅与前一个[
和最后一个]
匹配,而不处理中间的所有内容)
rather than an array with separate strings: 而不是带有单独字符串的数组:
"[test,string,0,5,bob,0,1]",
"[age,number,1,100,20,0,1]",
"[male,const,0,0,yes,200,1]",
JS .split(',') obviously takes every single comma into account and splits on all of them rather than just the commas outside the []
. JS .split(',')显然将每个逗号都考虑在内并且对所有逗号进行分割,而不仅仅是[]
之外的逗号。 I think solution will be a regex? 我认为解决方案将是正则表达式? Thanks. 谢谢。
Your approach using str.match(/\\[(.*)\\]/g)
is very good, it just needs a little adjustment. 您使用str.match(/\\[(.*)\\]/g)
方法非常好,只需稍作调整即可。 Instead of using .*
which will match every character you should use [^\\]]
to match every character except a closing bracket. 不要使用.*
来匹配每个字符,而应该使用[^\\]]
来匹配除右括号之外的所有字符。
const str = "someID,[test,string,0,5,bob,0,1],[age,number,1,100,20,0,1],[male,const,0,0,yes,200,1]"; console.log(str.match(/\\[[^\\]]+\\]/g))
\\[
Match an opening bracket \\[
匹配左括号 [^]
Match all characters not in this set [^]
匹配此集合以外的所有字符 [^\\]]
Match all characters execpt ]
[^\\]]
匹配所有字符execpt ]
[^\\]]+
Match one ore more charcters that are not ]
[^\\]]+
匹配一个或多个charcters不在]
\\]
Match a closing bracket \\]
匹配一个右括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.