Jumbalaya Wanton
Jumbalaya Wanton

Reputation: 1621

Regexp match optional group unless it's got something inside it

I'm playing around with this regexp: http://regex101.com/r/dL3qX1

!\[(.*?)\](?:\(\)|\[\])?

All the below strings should match. However, should the second set of brackets, that is optional, contain anything within it, the regexp should match nothing.

// Match
![]
![caption]
![]()
![caption]()
![][]
![caption][]

// No match
![][No match]
![caption][No match]
![](No match)
![caption](No match)

I should still be able to match examples that have text at the end of the line.

![] hello
![caption][] hi there

In other words, I only want a match if there is no optional group, or if there is, I only want a match if the optional group is empty (nothing between the brackets).

Is what I'm after possible?

Upvotes: 1

Views: 121

Answers (2)

anubhava
anubhava

Reputation: 784998

You can use this regex:

^!\[[^\]]*\](?:\(\)|\[\])?$

Working Demo: http://regex101.com/r/eX0sR8

Note use of [^\]]* instead of .*? in the first square brackets which makes sure to match until very first ]. Also better to use line start/end anchors ^ and $

Upvotes: 1

Jerry
Jerry

Reputation: 71538

I personally prefer using negated class when it comes to brackets:

^!\[([^\[\]]*)\](?:\(\)|\[\])?$

regex101 demo

I substituted (.*?) to [^\[\]]*, added ^ and $ at the beginning and end respectively.

That is, if I understood what you're looking for correctly, only the first set is matching.

Upvotes: 2

Related Questions