'Regex to find content of the last occurence of square brackets

Hi Everybody,

I'm Currently using preg_match and I'm trying to extract some informations enclosed in square brackets.

So far, I have used this:

/\[(.*)\]/

But I want it to be only the content of the last occurence - or the first one, if starting from the end!

In the following:

string = "Some text here [value_a] some more text [value_b]"

I need to get:

"value_b"

Can anybody suggest something that will do the trick?

Thanks!



Solution 1:[1]

If you are only expecting numbers/letter (no symbols) you could use \[([\w\d]+)\] with preg_match_all() and pull the last of the array as the end variable. You can add any custom symbols by escaping them in the character class definition.

Solution 2:[2]

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

See it here on regexr

var someText="Some text here [value_a] some more text [value_b]";
alert(someText.match(/\[([^\]]*)\][^\[]*$/)[1]);

The part inside the brackets is stored in capture group 1, therefor you need to use match()1 to access the result.

For simple brakets, see the source to make this answer: Regex for getting text between the last brackets ()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Biotox
Solution 2