My JavaScript code needs to match text that meets the following criteria:
(
surrounded by parentheses)
[
surrounded by square brackets]
- not surrounded by either type of bracket
Given the expression...
none[square](round)(accept]able)[wrong).text
... there should be 4 matches for none
, [square]
, (round)
, and (accept]able)
. However, [wrong)
should not match as it lacks a closing ]
.
In my attempted regex found at this link...
([([])[A-Za-z]+[\])]|[^\[()\]]+
...issues arose where (accept]
, able
, and [wrong)
matched incorrectly. I prioritize correct matching over partial matches with unbalanced brackets.
To improve my regex, I believe I need to adjust the [\])]
expression based on the initial matching group, using )
if starting with (
or ]
if starting with [
.
I've experimented with conditional expressions. While they work in some regex engines like PCRE and Python, I encountered issues when implementing them in JavaScript (see here).
Can this challenge be tackled solely through a JavaScript regex solution, or will it require separate handling in a complex JavaScript function?