0

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?

soupagain
  • 1,123
  • 5
  • 16
  • 32

4 Answers4

2

Try this, uses a negative look ahead assertion

\[[^\[]*\](?!\[)$
Paul Creasey
  • 28,321
  • 10
  • 54
  • 90
1

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 ].
Gumbo
  • 643,351
  • 109
  • 780
  • 844
0

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.

Groovetrain
  • 3,315
  • 19
  • 23
0

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.

LHMathies
  • 2,384
  • 16
  • 21