Home > Back-end >  How can a closing bracket be dealt with inside a regex match?
How can a closing bracket be dealt with inside a regex match?

Time:12-23

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

This would be used in dart

EDIT: The text in the middle abc should not be part of the match, meaning Match #1 should be [quote...] and match #2 should be [/quote], as my current regex pattern does

CodePudding user response:

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]

If you want to have 2 matches per line for opening and closing tags then you can use:

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

RegEx Demo 2

CodePudding user response:

(?<=quote=)["'a-zA-Z\[\]] (?=]abc)|(?<=quote])(?=abc)

regex101.com

Where:

  1. (?<=quote=) - everything that goes after quote=, look-behind
  2. (?=]abc) - everything that goes before ]abc, look-ahead
  3. ["'a-zA-Z\[\]] - which symbols are allowed between parts 1 and 2.
  4. (?<=quote]) - everything that goes after quote], look-behind
  5. (?=abc) - everything that goes before =abc, look-ahead

CodePudding user response:

Try this one. Seems like working:

\[quote(?:=|=\s*(['"]))?([^\]]*)\1?\]([^\[]*)\[\/quote\]
  • Related