Javascript.match regular expression with inverse quantifier (or parsing from right to left)

For a line like ...

"ABCDEFG"

Is it possible to have a quantifier that works the other way around, so to speak?

For instance:

var foo = "ABCDEFG";
foo.match(/.{1,3}/g);

Results in:

// Array(3) ["ABC", "DEF", "G"]

What I'm trying to achieve:

// Array(3) ["A", "BCD", "EFG"]

Therefore, regardless of the length of the string, the array is always a representation of the string, with each length of node 3 characters (with the possible exception of the 1st), but always starts at the end of the string. Thus, the first element of the array can be 1, 2, or 3 characters long, simply depending on what is left.

I tried to use the following errors:

foo.match(/.{-1,3}/g); // null
foo.match(/.{1,-3}/g); // null

I think I could use negatives similar to dividing lines, however each of these examples returns null.

, - , , , .match(). , , ?

+4
3

, , :

var foo = "ABCDEFG";
foo.match(/.{1,3}(?=(.{3})*$)/g);  // ["A", "BCD", "EFG"]

(?=(.{3})*$) lookahead, (!) 3 , ($).

+4

, , .

, string .match(), array:

var matches = foo.split("").reverse().join("")
    .match(/.{1,3}/g).map(m => m.split("").reverse().join(""))
    .reverse();

:

  • foo.split("").reverse().join("") string.
  • .match() string.
  • .map(m => m.split("").reverse().join("")).
  • , , array.

Demo:

var foo = "ABCDEFG";

var matches = foo.split("").reverse().join("").match(/.{1,3}/g).map(m => m.split("").reverse().join("")).reverse();
console.log(matches);
+2

If you create your own regular expression, you can use it to pull matches in the correct order:

var foo = "ABCDEFG";
console.log(foo.match(new RegExp("(.{"+foo.length % 3+"})"+"(...)".repeat(Math.floor(foo.length / 3)))));
0
source

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


All Articles