Link to home
Start Free TrialLog in
Avatar of qwertq
qwertq

asked on

Help with regex

Yea i suck at writing regular expressions. From a string like this:

Foo (Bar)

I need to return Foo and Bar separately.  Thanks.
Avatar of Scripting_Guy
Scripting_Guy
Flag of Switzerland image

/([a-zA-Z]+) \(([a-zA-Z]+)\)/s
Avatar of qwertq
qwertq

ASKER

Thanks for the quick reply. I am having trouble getting it to eval on this string:

Test (Test: Red;Another: + 1.00)

Also, just to check - would it still return $hits[0] if the second part in the () is not there?
ASKER CERTIFIED SOLUTION
Avatar of Scripting_Guy
Scripting_Guy
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of qwertq

ASKER

Can't you use a * for everything inside the ()?
that would be the dot (.) making the regexp look like this:

'/([a-zA-Z]+) \((.+)\)/s'

however, i'm would not use the dot if there is an other way, because the dot will match some more stuff, e.g. like this

"Foo (Bar) Foo (Bar)"
Now this regexp will find two hits:
1. Foo
2. Bar) Foo (Bar

which is not quite what you might be expecting.
Avatar of ddrudik
$matches[2] would be empty if the string did not contain ( ):
Raw Match Pattern:
([^(]+)(?:\(([^)]*)\))?
 
PHP Code Example:
<?php
$sourcestring="your source string";
preg_match('/([^(]+)(?:\(([^)]*)\))?/',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>
 
$matches Array:
(
    [0] => Test (Test: Red;Another: + 1.00)
    [1] => Test 
    [2] => Test: Red;Another: + 1.00
)

Open in new window