Target string:
Come to the castle [Mario], I've baked you [a cake]
I want to match the contents of the last brackets, ignoring the other brackets ie
a cake
I'm a bit stuck, can anyone provide the answer?
Try this, uses a negative look ahead assertion
\[[^\[]*\](?!\[)$
This should do it:
\[([^[\]]*)][^[]*(?:\[[^\]]*)?$
\[([^[\]]*)]
matches any sequence of […]
that does not contain [
or ]
;[^[]*
matches any following characters that are not [
(i.e. the begin of another potential group of […]
);(?:\[[^\]]*)?$
matches a potential single [
that is not followed by a closing ]
.You could use some sort of a look-ahead. And because we don't know the precise nature of what text/characters will have to be processed, it could look something like this, but it will need a little work:
\[[a-z\s]*\](?!.*\[([a-z\s]*)\])
Your contents should be matched in \1, or possibly \2.
Simple is best: .*\[(.*?)]
will do what you want; with nested brackets it will return the last, innermost one and ignore bad nesting. There's no need for a negative character class: the .*?
makes sure you don't have any right brackets in the match, and since the .*
makes sure you match at the last possible spot, it also keeps out any 'outer' left brackets.