Reputation: 93
I want to match strings in parentheses (including the parens themselves) and also match strings when a closing or opening parenthesis is missing.
From looking around my ideal solution would involve conditional regex however I need to work within the limitations of javascript's regex engine.
My current solution that almost works: /\(?[^()]+\)|\([^()]+/g
. I could split this up (might be better for readability) but am curious to know if there is a way to achieve it without being overly verbose with multiple |
's.
Might help to understand what I'm trying to achieve through examples (highlighted
sections are the parts I want to match):
(paren without closing
(paren in start)
of string(in middle)
of string(at end of string)
paren without opening)
(string with only paren)
(with multiple)
parens (in a row)
Here's a link to the tests I set up in regexr.com.
Upvotes: 0
Views: 4060
Reputation: 110665
You can match the following regular expression.
^\([^()]*$|^[^()]*\)$|\([^()]*\)
Javascript's regex engine performs the following operations.
^ # match the beginning of the string
\( # match '('
[^()]*. # match zero or more chars other than parentheses,
# as many as possible
$ # match the end of the string
| # or
^ # match the beginning of the string
[^()]*. # match zero or more chars other than parentheses,
# as many as possible
\) # match ')'
$ # match the end of the string
| # or
\( # match '('
[^()]*. # match zero or more chars other than parentheses,
# as many as possible
\) # match ')'
Upvotes: 3
Reputation: 339
As of question date (May 14th 2020) the Regexr's test mechanism was not working as expected (it matches (with multiple)
but not (in a row)
) Seems to be a bug in the test mechanism. If you copy and paste the 8 items in the "text' mode of Regexr and test your expression you'll see it matches (in a row)
. The expression also works as expected in Regex101.
Upvotes: 0
Reputation: 818
I think you've done alright. The issue is that you need to match [()] in two places and only one of them needs to be true but both can't be false and regex isn't so smart as to keep state like that. So you need to check if there is 0 or 1 opening or 0 or 1 closing in alternatives like you have.
Update:
I stand corrected since all you seem to care about is where there is an open or closing parenthesis you could just do something like this:
.*[\(?\)]+.*
In English: any number of characters with eith an ( or ) followed by any number of characters. This will match them in any order though, so if you need ( to be before closed even though you don't seem to care if both are present, this won't work.
Upvotes: -1