Parteek Dheri
Parteek Dheri

Reputation: 99

Regex to match content of bracket

I want to grab content of bracket in a line. The bracket can be () or [].

I have written this [\[\(].*[\)\]] but it matches (something] too. I want to match (some) or [this] and not [this) Can you guide me?

Upvotes: 1

Views: 187

Answers (4)

Valdi_Bo
Valdi_Bo

Reputation: 30971

I assume, that the content between either square or round brackets can include neither "own" brackets nor "other" brackets, so chars like: [, ], ( and ) are forbidden in the content to match.

To make the regex more useful, I put 2 capturing groups, #1 between [ and ] and #2 between ( and ), to assist in determining which brackets are around the content caught.

To match the content between square brackets (with a capturing group) you need:

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

and to match the content between round brackets (parenthesses, also with a capturing group) you need:

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

Both above "partial" regexes (for each variant) are alternatives in the final regex, so they are separated with |.

So, the full regex is:

\[([^\[\]()]+)\]|\(([^\[\]()]+)\)

In case of source text like [xxxx], xxxx will be captured as group 1, whereas in case of (yyyy), yyyy will be captured as group 2.

Upvotes: 1

Mohammad Usman
Mohammad Usman

Reputation: 39322

Instead of using single complex regular expression, you may use alternatives i.e:

\[.+?\]|\(.+?\)

Regex101 Example:

Description:

  • \[ matches the character [ literally.
  • .+? matches any character except for line terminators.
  • +? quantifier matches between one and unlimited times, as few times as needed.
  • \] matches the character ] literally.
  • | allows alternatives, acts like Boolean OR.
  • Regular expression to the right of | is similar as described above.

Upvotes: 1

CodeHunter
CodeHunter

Reputation: 2082

[?(\[)[\]]|[\)]]+

might help you if you are sure that your strings are going to be contained inside (...) or [...]. ] Your previous expression won't work because you are trying to match this condition: either [ or ( in beginning and either ] or ) in the end. What you need is a conditional: if [ in beginning then ] in end or if ( in beginning then ) in the end which I stated above.

Upvotes: 0

Davide Visentin
Davide Visentin

Reputation: 741

A possible solution is [(\(.*\))(\[.*\])]. In that case the regex match the sequence (+whatever+) OR the sequence [+whatever+].

Upvotes: 1

Related Questions