Improve JavaScript regex to match content inside of tags with or without closing tag, excluding self

Viewed 263

Preface: I'm aware about general consensus standing against using regex to parse HTML. Asking you in advance, please avoid any recommendations in this regard.


Explanations.

I have the following regex

/<div class="panel-body">([^]*?)(<\/div>|$)/gi

It matches all content, including self, inside of the the div with class .panel-body

Full match:

<div class="panel-body">
   <a href="#">Link</a>
   Line 1
   Line 2
   Line 3
</div>

.. it also matches content with no closing div tag.

Full match:

<div class="panel-body">
   <a href="#">Link</a>
   Line 1
   Line 2
   Line 3
   Don't match after closing `div`...but match this and below in case closing `div` is removed.
   Line below 1
   Line below 2
   Line below 3

Question.

How could I improve my regex to do the following:

  1. Not include in the full match <div class="panel-body"> and closing </div> (when there is closing div tag)

  2. To do this straight (if possible) into the full match without using groups

regex101.com example


Edit 1:

The string doesn't start with <div class="panel-body">, it starts with

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Webmin 1.851 on centos.centos (CentOS Linux 7.3.1611)</title>
</head>
<body>
<div>
<div>
<div class="panel-body">

* Note: It's never closed until the full load as it's progressive output.

Edit 2:

After posted answers, I made speed comparison tests. It's up to you, whose solution would serve best for you.

Speed-test Results
4 Answers
Related