T
T
tyoma_koder2021-11-21 11:42:06
Regular Expressions
tyoma_koder, 2021-11-21 11:42:06

Is it possible to make a regular expression for unclosed brackets?

The regular will be in js. I use iblize to enter text, and there is syntax highlighting on regular expressions, I would like to just add a regular expression to its source code and not use mutationobserver on the block in which it generates spans. Interested in parentheses only

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
antares4045, 2021-11-21
@antares4045

There is no recursion in native javascript regexp. Accordingly, of course, you can write a construction with a limitation of some depth of nesting by hand (although it’s more likely to generate it).
The problem is not new, and bike builders periodically release their versions of regular expressions (Yandex gave me such a link in response to the request "js recursive regex" )
But judging by the context of the question, a non-native regexp will not work for you, so in general, your task is not solvable.
UPD.
about manual generation:
for a nesting depth of 3, I got this Frankenstein:

/^[^()]*(\([^()]*(\([^()]*(\([^()]*\))*[^()]*\))*[^()]*\))*(?<unclosed>\([^()]*(\([^()]*(\([^()]*\))*[^()]*\))*[^()]*)*[^()]*(\([^()]*(\([^()]*(\([^()]*\))*[^()]*\))*[^()]*\))*[^()]*$/

-- if you find an unclosed group, then there is a problem
(I think the main idea is visible)
UPD2:
the generator looks something like this, only the site regex101 from my regular to a depth of 150 has died. so maybe a dead end idea.
const anySymbols = `[^()]*`
const closedRegexPattern = (depth) => {
    if(depth < 1)
        return anySymbols  
    return `\\((${anySymbols}${closedRegexPattern(depth-1)})*${anySymbols}\\)`
}
const unclosedCatcherRegexPattern = (depth) => {
    const unclosedPart = `(?<unclosed>\\((${anySymbols}${closedRegexPattern(depth-1)})*${anySymbols})*`
    return `^${anySymbols}${closedRegexPattern(depth)}${unclosedPart}${closedRegexPattern(depth)}${anySymbols}$`
}

console.log(unclosedCatcherRegexPattern(150))

By the way, in my regular season from UPD1 there was a jamb, because of which the option ((1)(2)) was valid, but ((1)3(2)) was no longer valid.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question