Search code examples
regexpcre

Disallow empty content in a BBCode tag with an attribute


I have this regex:

\[code(?:=(["']?)(.{0,50}?)\1)?\](?!\s*\[\/code\])(.*?)\[\/code\]

This regex is supposed to support:

[code]content[/code]
[code=Title]content[/code]
[code="Title"]content[/code]
[code='Title']content[/code]

Empty contents [code][/code] are not allowed and this is done thanks to:

(?!\s*\[\/code\])

Also empty contents with title [code=Title][/code] are not allowed, and the above non-capturing group is working also for that condition, until I do not insert two tags together:

[code="title"][/code]
[code][/code]

How can I not make match the last condition by the regex?
The problem can best be observed here: https://regex101.com/r/J1dwJa/2/

As I understand, what it is creating problems is this part of the regex:

(["']?)

I am using the quantifier in order to support the pattern [code=Title][/code]. What this regex needs, at least I think, is that when it encounters ] should stop and do not go on. I am trying but I am not finding any path with my basic regex knowledge.


Solution

  • You should care about two things:

    1. . would match much more than needed

    2. You shouldn't match a [/code] in content part while looking for the closing [/code]

    \[code(?>=(["']?)([^][]*)\1)?](?:(?!\s*(\[\/code])).)+(?3)
    

    See live demo here