2

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!

  • 2
    Use `preg_match_all` and just the value you want. And more importantly: Make the quantifier lazy: `.*?`. – Felix Kling Jan 05 '12 at 21:34
  • 2
    @FelixKling: no need for the lazy quantifier, just use a complemented character class -- see my answer. In fact, you should learn to _avoid_ lazy quantifiers when you can. – fge Jan 05 '12 at 21:36
  • @fge: True, will be faster... he should still use `preg_match_all`. – Felix Kling Jan 05 '12 at 21:37
  • Well, if it's only for the last match, no need -- let `.*` slurp it all and backtrack to find the first `[` – fge Jan 05 '12 at 21:39

3 Answers3

5

Match against:

/.*\[([^]]+)\]/

using preg_match (no need for the _all version here, since you only want the last group) and capture the group inside.

Your current regex, with your input, would capture value_a] some more text [value_b. Here, the first .* swallows everything, but must backtrack for a [ to be matched -- the last one in the input.

fge
  • 119,121
  • 33
  • 254
  • 329
0

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

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 ()

Fabrício Pereira
  • 1,521
  • 1
  • 12
  • 20
0

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.

Biotox
  • 1,563
  • 10
  • 15
  • Thanks for pointing that out! In my case, I'm retrieving two numbers separated by a forward slash, so I guess it wouldn't work. Plus I wanted to keep it simple. But it's good to know! – Ben Baudart Jan 05 '12 at 23:39
  • You can escape a forward slash into the character class definition `:)` So, something like `\[(\d+\/\d+)\]` for a number-slash-number – Biotox Jan 06 '12 at 17:58