Governor
Governor

Reputation: 27

How to exclude character that has preceding character different than specified in regular expression?

With regular expression I would like to get all characters between round brackets, but \( and \) characters should be also included in the result.

Examples:

input: fo(ob)a)r
output: ob

input: foo(bar\(qwerty\))baz
output: bar\(qwerty\)

This is what I used for finding text between brackets: (?<=\()([^\s\(\)]+)(?=\)), but I can't make exceptions for brackets preceded by \.

Upvotes: 0

Views: 38

Answers (2)

Seblor
Seblor

Reputation: 7136

You could do something like this :

.*(?<!\\)\((.*?)(?<!\\)\)

Basically, it matches as many characters as possible until it sees an open parenthesis without a backslash (using a negative lookbehind), then groups the next matching characters until a closing parenthesis (still without a backslash).

Note that this regex may not work properly if you escape the backslashes.

Example : https://regex101.com/r/BqVKZp/1

Upvotes: 2

Ildar Akhmetov
Ildar Akhmetov

Reputation: 1431

This regex works for both your examples, without any lookaheads and lookbehinds:

\((.+[^\\])\)

A U flag is needed.

Upvotes: 0

Related Questions