Match entire line, group all occurrences of a sequence and everything inbetween

Viewed 63

Let's take this line for example:

This is a [13125] string and [9414] it's long. [123897] it's longer [38153] than an average [73941].

How do I match entire line and group every occurence of [number] and everything in between?

I have this regex so far: /(.*)(\[\d*\])(.*)/. It works as intended but only groups the last occurrence of [number]. I want it to do something like this:

Group 1: This is a 
Group 2: [13125]
Group 3:  string and 
Group 4: [9414]
...
3 Answers

Here you go with RegEx like this

const str = "This is a [13125] string and [9414] it's long. [123897] it's longer [38153] than an average [73941]";

// Match [number] OR everything before [number]
// globally with g flag
const m = str.match(/((\[\d+\])|(.*?)(?=\[\d+\]))/g);

console.log(m)

'use strict';

const regex = /([a-z '.]+)([[\]\d]+)/gmi;
const string = "This is a [13125] string and [9414] it's long. [123897] it's longer [38153] than an average [73941].";
const matches = [...string.matchAll(regex)] // matchAll to include capture groups
  .map(([, str, n]) => ([str, n])) // exclude full match and metadata
  .flat()
  .reduce((obj, val, i) => (obj['Group ' + (+i + 1)] = val) && obj, {}); // label Group 1, Group 2, etc.
console.log(matches);
/*
{
  'Group 1': 'This is a ',
  'Group 2': '[13125]',
  'Group 3': ' string and ',
  'Group 4': '[9414]',
  'Group 5': " it's long. ",
  'Group 6': '[123897]',
  'Group 7': " it's longer ",
  'Group 8': '[38153]',
  'Group 9': ' than an average ',
  'Group 10': '[73941]'
}
*/

You could split on the parts that has numbers between the square brackets, and use a capturing group to keep the values in the result.

(\[\d+])

let s = "This is a [13125] string and [9414] it's long. [123897] it's longer [38153] than an average [73941]."
s = s.split(/(\[\d+])/);
console.log(s);

Related