Search code examples
regex

RegEx capture everything before keyword but after the opening bracket


Test string:

[valign px=-2][center][bgcolor=GREEN]TESTING[/bgcolor][/center][/valign]

I have come up with color.*?\] which almost works... It gets everything after the keyword up to and including the closing bracket:

color=GREEN]  AND  color]   ---> Target ---> [bgcolor=GREEN]  AND  [/bgcolor]

I just can't get how to make the same in reverse

\[.*?color.*?\] this gets me the whole string before the key up to the closing bracket - [valign px=-2][center][bgcolor=GREEN] BUT it also correctly gives me [/bgcolor] without TESTING in between them

I'm using https://regex101.com/ for testing


Solution

  • If you want to get [bgcolor=GREEN] and [/bgcolor] with leading lowercase characters for color and uppercase chars for color for the value, you might use:

    \[\/?[a-z]*color(?:=[A-Z]+)?]
    

    See a regex 101 demo

    Or a bit more broader match using a negated character class denoted with [^

    \[[^][=]*color(?:=[^][=]+)?]
    

    The regex in parts matches:

    • \[ Match [
    • [^][=]* Match 0+ times any character except [ ] or =
    • color Match literally
    • (?:=[^][=]+)? Optionally match = and 1+ times any char except [ ] or =
    • ] Match literally

    See a regex 101 demo