user2516837
user2516837

Reputation:

Match last string between special characters

I want to get the last string between special characters. I've done for square bracket as \[(.*)\]$

But, when I use it on something like Blah [Hi]How is this[KoTuWa]. I get the result as [Hi]How is this[KoTuWa].

How do i modify it to get the last stringthat is KotuWa.

Also, I would like to generalise to general special characters, instead of just matching the string between square brackets as above.

Thanks, Sai

Upvotes: 2

Views: 87

Answers (3)

Cristian Lupascu
Cristian Lupascu

Reputation: 40526

You can require that the string between brackets does not contain brackets:

Edit: thanks to funkwurm and jcubic for pointing out an error. Here's the fixed expression:

\[([^[]+)\][^\[]*$

If you need to use other separators than brackets, you should:

  • replace the \[ and \] with your new separators
  • replace the negative character classes with your beginning separator.

For example, assuming you need to use the separators <> instead of [], you'd do this:

<([^<]+)>[^\>]*$

Upvotes: 0

asontu
asontu

Reputation: 4659

I would do this:

[^[\]]+(?=][^[\]]*$)

Regular expression visualization

Debuggex Demo

To extend this to other types of brackets/special chars, say I also wanna match curly braces { and double quotes ":

[^{}"[\]]+(?=["\]}][^{}"[\]]*$)

Regular expression visualization

Debuggex Demo (I added the multi-line /m only to show multiple examples)

Upvotes: 4

Maurice Perry
Maurice Perry

Reputation: 32831

Here is one way to do it:

   \[([^\[]*)\]$

Upvotes: 0

Related Questions