简体   繁体   中英

Regex to split Javascript string into two strings

I'm searching for a way to parse all occurrences of string in a file between two patterns. I have:

var test = "XXXX\n sssssssss\n1111\nXXXX\nssssssssss ssss\nXXXX\nssssssssssssss\n1111111111\nXXXX\n"  
var testRE = test.match(/XXXX\n([.\n]+)XXXX/g);
console.log(testRE); // null

This regex like many others I've tried doesn't get me the result I want. I want a regex which will match all occurrences in order to have a result like this:

[' sssssssss\n1111\n', 'ssssssssss ssss\n', 'ssssssssssssss\n1111111111\n']

Anyone have an ideas?

Potentially you could solve this using the String.split method, for example:

var value = "XXXX\n sssssssss\n1111\nXXXX\nssssssssssssss\nXXXX\nssssssssssssss\n1111111111\nXXXX\n"  
var items = value.split("XXXX\n");
console.log(items);

Output:

>>> ["", " sssssssss\n1111\n", "ssssssssss ssss\n", "ssssssssssssss\n1111111111\n", ""]

You could strip empty values from the start and end of items like so if required:

if (items[0].length == 0) {
    items = items.slice(1);
}
if (items[items.length - 1].length == 0) {
    items = items.slice(0, items.length - 1);
}

Or simply filter out all empty values:

items = items.filter(function(n){ return n.length != 0 });

Stripping/filtering the items provides the result suggested as an example in your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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