简体   繁体   English

JavaScript 正则表达式字符串拆分

[英]JavaScript Regular Expression String Split

What I have is a string that I want to split.我拥有的是一个我想拆分的字符串。

I can set delimiters inside the string for example:我可以在字符串中设置分隔符,例如:

+++DELIMITER 1+++

text

+++DELIMITER R+++

text 2

+++NAME OF DELIMITER+++

text n

...

Edits after questions:问题后编辑:

The string does not contain linefeed characters, An example of string wourld be:字符串不包含换行符,字符串的一个例子是:

let string = "+++DELIMITER 1+++ text +++DELIMITER R+++ text 2 +++NAME OF DELIMITER+++ specialchars \"£$%%£$\"<>";

text n";

What i want to obtain is an array constructed like this:我想获得的是一个这样构造的数组:

resultarray=[
     ["DELIMITER 1", "text"],
     ["DELIMITER R", "text 2"],
     ["NAME OF DELIMITER", "text n"]
     ...
];

I think I have to use String.split method, but I don't know what kind of regex to use.我想我必须使用 String.split 方法,但我不知道使用什么样的正则表达式。

You could split the string and reduce single strings to pairs.您可以拆分字符串并将单个字符串减少为成对。

 var string = '+++DELIMITER 1+++text+++DELIMITER R+++text 2+++NAME OF DELIMITER+++text n', parts = string .split(/\\+{3}/) .slice(1) .reduce((r, s, i) => r.concat([i % 2 ? r.pop().concat(s) : [s]]), []); console.log(parts);

Here you go (step by step):给你(一步一步):

 const str = ` +++DELIMITER 1+++ text +++DELIMITER R+++ text 2 +++NAME OF DELIMITER+++ text n ` // first replace the +++ with '' const strr = str.replace(/\\+{3}/g, '') // place them in an array const strArr = strr.split('\\n').filter(r=>r!=='') //push each next two values in separate array const finalArr = [] while(strArr.length) finalArr.push(strArr.splice(0,2)) console.log(finalArr)

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

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