I want to write a regular expression in JavaScript that works unconditionally WRT the presence (or absence) of an optional substring within a repeated pattern. (In other words, I want it to work whether or not the substring is present.)
In the example below, consider the repeated pattern to begin with the string beg and end with the string end. The data I seek to extract are the strings foo, bar, baz, bat and qux. As you can see, the complication is the presence of the optional substring bat and what surrounds it.
Below is the example to solve.
Example
To see the live demo, click here.
https://regex101.com/r/jZ7sU3/1
Consider the following regular expression:
/beg(.*?)end/g
acting on the following content:
beg foo end beg bar end beg baz (bat) end beg qux end
produces the following result:
Match 1:
fooMatch 2:
barMatch 3:
baz (bat)Match 4:
qux
but the result I seek is as follows:
Match 1:
fooMatch 2:
barMatch 3:
bazMatch 4:
batMatch 5:
qux
Can anyone figure out the solution?
data\d, if that's what you're trying to retrieve.