Isaac Ferreira
Isaac Ferreira

Reputation: 436

Keep the outer brackets matching without repeating the inner pattern

How can I rewrite this regular expression /\[.+\]|\{.+\}/ but without repeating the inner pattern /.+/?

Must match:

Mustn't match:

Upvotes: 0

Views: 38

Answers (1)

The fourth bird
The fourth bird

Reputation: 163372

In your regex you could make the .+ non greedy .+?. When greedy, this would match from the opening [a till the closing b] in this string:

[abc] {a} [b].

Without the .+ or .+? you might use \[[^[\n]+?]|{[^{\n]+?} as an alternative.

This would match:

\[       # Match [
[^[\n]+? # Match not [ or a newline one or more times non greedy
]        # match ]
|        # Or
{        # Match {
[^{\n]+? # Match not { or a new line one or more times non greedy
}        # match }

Or if this is only about abc, you could use \[abc]|{abc}

When running both regexes on regex101.com and prce selected, they give the same number of execution steps so I think that this would not be faster.

\[.+?\]|\{.+?\}

\[[^[\n]+?]|{[^{\n]+?}

Upvotes: 1

Related Questions