Split string data into an array based on a new string and then a two-digit number

What I want to do is split the data from the string into an array.

Here is the general idea of ​​a text format ...

xxxxx denotes any combination of alpha-numeric whitespace data.

xxxxx
 1 xxxxxxxxxx
 2 xxxxxxxxxx
xxxxxxxxx
xxxxxxxxx
xxxxxxxx
 3 xxxxxxxxxx
 4 xxxxxxxxxx
xxxxxxxxxx
 5 xxxxxxxxxx

(When numbers fall into double digits, ten places fall into the empty position before the number)

Now what I want to do is to have an array of 5 elements (in this case) that stores the number and all the data that is being tracked (including new lines). It used to be unimportant, and I could use it string.split("\n"), but now I need to distinguish based on some kind of regular expression, for example /\n [0-9]{1,2}/, so I'm looking for a quick and easy way to do this (as split () does not support regular expression).

I want the array to be like

array[1] = " 1 xxxxxxxxxx"
array[2] = " 2 xxxxxxxxxxx\nxxxxxxxxxx\nxxxxxxxxxx"
array[3] = " 3 xxxxxxxxxx"
...etc
+3
3

lookahead (?= [1-9] |[1-9][0-9] ), , , xxxx. , .

var text =
  "preface\n" +
  " 1 intro\n" +
  " 2 body\n" +
  "more body\n" +
  " 3 stuff\n" +
  "more stuff\n" +
  "even 4 stuff\n" +
  "10 conclusion\n" +
  "13 appendix\n";

print(text.split(/^(?= [1-9] |[1-9][0-9] )/m));

( ideone.com):

preface
, 1 intro
, 2 body
more body
, 3 stuff
more stuff
even 4 stuff
,10 conclusion
,13 appendix
+2

split() . :

text.split(/\n(?=[1-9 ][0-9] )/)
+5

@polygenelubricants, , .

, , - . . , , , , , , .

function SplitCrazyString(str) {
    var regex = /(\n\s?\d+\s[^(\n\s?\d+)]+)/mg;

    var tempStr = str.replace(regex, "~$1");

    var ary = tempStr.split('~');

    for (var i = 0; i < ary.length; i++) {
        ary[i].replace('~', '');
    }

    return ary;
}
var x = "xxxxx\n" +
    " 1 xxxxxxxxxx\n" +
    " 2 xxxxxxxxxx\n" +
    "xxxxxxxxx\n" +
    "xxxxxxxxx\n" +
    "xxxxxxxx\n" +
    " 3 xxxxxxxxxx\n" +
    " 4 xxxxxxxxxx\n" +
    "xxxxxxxxxx\n" +
    " 5 xxxxxxxxxx\n";
var testStr = "6daf sdf84 as96\n" +
    " 1 sfs 4a8dfa sf4asf\n" +
    " 2 s85 d418 df4 89 f8f\n" +
    "65a1 sdfa48 asdf61\n" +
    "w1c 987a w1ec\n" +
    "a6s85 d1a6f 81sf\n" +
    " 3 woi567 34ewn23 5cwe6\n" +
    " 4 s6k 8hf6 9gd\n" +
    "axxm4x1 dsf615g9 8asdf1jt gsdf8as\n" +
    " 5 n389h c8j923hdha 8h3x982qh\n";

var xAry = SplitCrazyString(x);
var testAry = SplitCrazyString(testStr);
+1

Source: https://habr.com/ru/post/1750733/


All Articles