select string from round bracket

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
rahulsonar
Forum Newbie
Posts: 10
Joined: Wed Mar 11, 2009 8:54 am

select string from round bracket

Post by rahulsonar »

Hi All,

I have a pattern like this:

RS-1.75 m(TE)

from which, I want to select string from round brackets ( in this case, TE). Can anyone help me in regex or any other way to do this?

Thanks,
ouchiko
Forum Commoner
Posts: 35
Joined: Sun Oct 09, 2011 6:54 pm
Location: London

Re: select string from round bracket

Post by ouchiko »

Code: Select all

$string = "This is a (IE) test about the this (UY)";
preg_match_all("/\((.*)\)/U",$string,$results);


foreach ($results[1] as $ID ) print $ID . "<BR>";
Tosha
Forum Newbie
Posts: 1
Joined: Wed Dec 28, 2011 4:33 pm

Re: select string from round bracket

Post by Tosha »

Thank you for this response. I had the very same question. This looks like it would work, but I am a little confused about the /U modifier. It seems that this would cause some problems, I might be wrong about this. Is there another approach that I can take in this situation, or is this the best way? I will need to work this issue out before I can move forward on the human resource management software that I have under development. As of now, this little snippet is causing bugs all over the place, so hopefully someone has some helpful advice. Thank you.
Last edited by Tosha on Wed Jan 04, 2012 9:20 am, edited 1 time in total.
User avatar
ragax
Forum Commoner
Posts: 85
Joined: Thu Dec 15, 2011 1:40 pm
Location: Nelson, NZ

Re: select string from round bracket

Post by ragax »

Yes, ouchiko's pattern works, but...
I would not recommend it.
Why? Because it uses an uncommon (and potentially confusing) modifier: /U
This pattern modifier says "swap the greediness status of the star and question mark quantifiers". So in this expression, the "greedy star" is lazy!!! That means you have a non-standard regex that will break almost everywhere except in this particular context.

Making only slight modifications to ouchiko's code, I would suggest something much more conventional:

Code: Select all

<?php 
$string = "This is a (IE) test about the this (UY)";
preg_match_all(",\(([^)]*)\),",$string,$results);
foreach ($results[1] as $ID ) print $ID . "<br />";
?>
In the capturing parentheses, instead of capturing everything, we capture anything that is not a closing parenthesis.

Note: This is only a starting point on the wide topic of capturing the content inside parentheses. For nested sets of parentheses, you may have to use a recursive regex.

Wishing you all a beautiful end of the year.
Post Reply