javascript regex match between two strings and count the number of characters inside

Viewed 81

I'm very new to js and programming, and i'd appreciate some help.

Suppose I have the following array (It is a single element array, they are not seperate elements)

var array =
[
     'Foo\n' +
      'bar23123\n' +
      'barbarfoo\n' +
      'foo, bar foo\n' +
      'foo\n' +
      '\n' +
      '\n' +
      'Bar\n' +
      '\n' +
      '\n'
  ]

Assuming there are multiple elements in the array, how can I write a regex expression to count and match the number of literal '\n' in between Foo\n and Bar\n in each element.

I wrote a partial solution to iterate through and return the count of all \n but how do I narrow my search to only return the values in between the two strings?

Here is the code:

let slashN = [];
for(let slash of array){
   var reg = RegExp('\\n' , 'g')
  slashN.push(slash.match(reg).length)
}

console.log(slashN);

I get the correct count, but I want to refine the regex expression.

Any help is highly appreciated.

1 Answers

You may use

var reg = /(?<=Foo\n.*?)\n(?=.*?Bar\n)/gs;

See the regex demo. Details:

  • (?<=Foo\n.*?) - a positive lookbehind that matches a location that is immediately preceded with Foo + newline and then any 0 or more chars, as few as possible
  • \n - a newline
  • (?=.*?Bar\n) - a positive lookahead that matches a location immediately followed with any 0+ chars as few as possible and then Bar + newline.

JavaScript demo:

var array =
[
     'Foo\n' +
      'bar23123\n' +
      'barbarfoo\n' +
      'foo, bar foo\n' +
      'foo\n' +
      '\n' +
      '\n' +
      'Bar\n' +
      '\n' +
      '\n'
];
let slashN = [];
for(let slash of array){
  var reg = /(?<=Foo\n.*?)\n(?=.*?Bar\n)/gs;
  slashN.push(slash.match(reg).length)
}

console.log(slashN);

Related