tags:

views:

27

answers:

2

Guys i have a small and frankly stupid problem, so here it is...

I have a text that could possibly include words,numbers etc. All i want is to match the numbers inside brackets, but withtout matching them like this:

Lorem 43 ipsum dolor 1 sit amet (355) some other text.

All i want to match is the number 355, but since there are numbers without brackets, i get to this:

\(\b\d+\b\) - 1st variant
\(.+?\)     - 2nd variant

presumably i get (355), but my php script is already under heavy load, matching to remove the brackets is not a n option.

A: 

Just match like your 1st variant, but capture only the digits in a group, like this

\((\d+)\)

And I think PHP supports named capture groups, so you could name it, so you aren't looking it up by index, like this I think

preg_match('/\((?<MatchedNumber>\d+)\)/', $searchText, $groups);
print_r($groups['MatchedNumber']);
Chad
Strange but it doesn't work, still matches the brackets
Anonymous
@Anonymous, don't check `$groups[0]`, it's in `$groups[1]` or `$groups['MatchedNumber']` see my edit (assuming my syntax is correct)
Chad
Thanks i forgot that preg_match returns array. Thanks once again. You saved me.
Anonymous
You probably don't need the `\b` since you are matching both sides explicitly.
Douglas Leeder
@Douglas Leeder, correct, they aren't needed, I had just copied Anonymous' regex. Removed them now though
Chad
+3  A: 

If you like you can remove the \b's in the first one; they don't hurt anything but they're redundant. To capture the number and exclude the parentheses, use unescaped parentheses around the digits:

\((\d+)\)

This will capture the digits for later use. For example:

preg_match('/\((\d+)\)/', $sentence, $matches);
var_dump($matches[1]);
John Kugelman
What i want is to match the numbers without the brackets: i.e. (355) -> 355.
Anonymous
@Anonymous that's exactly what this does
Sean Huber
Thanks too the solution is working too.
Anonymous
Yeah i forgot preg_match returns array
Anonymous