Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can a closing bracket be dealt with inside a regex match?

I’m trying to match a set of text inside a bracketed item as a match group.

That text may or may not itself have a bracket in it. To complicate matters, the text may or may not have quotes around it or exist at all, here are some examples of expected output:

[quote=John]abc[/quote] // John
[quote="John"]abc[/quote] // "John"
[quote='John']abc[/quote] // 'John'
[quote='Joh]n']abc[/quote] // 'Joh]n'
[quote='Joh[]n']abc[/quote] // 'Joh[]n'
[quote]abc[/quote] // match

The pattern I’ve come up with so far is \[quote[=]?["]?([\s\S]*?)["]?\]|\[\/quote\] but it is failing with the 4-5 examples above because it is seeing the first closing bracket

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This would be used in dart

>Solution :

You may use this regex:

\[quote(?:=(.+?))?][^\]\[]*\[/quote]

RegEx Demo

RegEx Breakdown:

  • \[quote: Match [quote
  • (?:: Start non-capture group
    • =: Match a =
    • (.+?): Match 1+ of any character and capture in group #1
  • )?: End non-capture group. ? makes this optional match
  • ]: Match closing ]
  • [^\]\[]*: Match 0 or more of any character that is not [ and ]
  • \[/quote]: Match [/quote]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading