简体   繁体   中英

Javascript regular expression can't split

I have some text like

<<<<((((sports====1000))))>>>> 

or

<<<<((((sports====1000))))((((librarys====2000))))>>>> 

my problem is I have get the text from this like

text[0][0] = 'sports';
text[0][1] = '1000';
text[1][0] = 'library';
text[1][1] = '2000';

any help will be greatly appreciated. Thanks in advance.

You could try to split on everything but the content and then remove the empty elements in the array.

s="<<<<((((sports====1000))))((((librarys====2000))))>>>>";
s.split(/[<()>=]/).filter(function(ele){if (ele!="") return true});
=> ["sports", "1000", "librarys", "2000"]

This is kind of a hack and since I don't know the syntax of your text this might or might not work out for you.

Yet another hack:

s="<<<<((((sports====1000))))((((librarys====2000))))((((no_value====))))>>>>";
arr = s.replace("====)","====nil").
  split(/[<\(\)>=]/).
  filter(function(ele){if (ele!="") return true});
var res=[]; 
for(var i = 0; i < arr.length; i+=2) { res.push([arr[i],arr[i+1]]); }
res
=> [["sports", "1000"], ["librarys", "2000"], ["no_value", "nil"]]

regex to get the elements could look like this:

\({4}(.+?)={4}(.+?)\){4}

see this example

Try this code.

var test  = "<<<<((((sports=====))))((((====2000))))((((hall====2000))))>>>>";
textAfterSplit1 = test.split(/[(<>)]/);

var myarray = [];

for (i=0; i <(textAfterSplit1.length); i++){
    textAfterSplit2 = textAfterSplit1[i].split(/[=]/);
    if (textAfterSplit2[0] == null){
        textAfterSplit2[0]= "";
    }
    if (textAfterSplit2[1] == null) {
        textAfterSplit2[1]= ""; 
    }
    myarray.push([textAfterSplit2[0],textAfterSplit2[1]]);
}

document.write(myarray[0][0]);
document.write(myarray[0][1]);
document.write(myarray[1][0]);
document.write(myarray[1][1]);

Intended output is:

sports2000

Its working in all scenarios. Hope this might help. Cheers!

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