tags:

views:

108

answers:

5

Given this text

"Foo(Bar)"

I'd like to extract "Bar" using a regex.

Help!

+4  A: 
/.*\((.*)\)/

The first .* will match anything before the parenthetical, the second .* (within a capture) will match anything inside the parenthetical and return it for you.

(I assumed that the quotes in your example text were not actually part of the string you're wanting to match.)

Amber
+1  A: 

If there are no nested brackets:

(?<=\().*?(?=\))
Philippe Leybaert
I Find this to be a bit OTT, it depends on what the OP wants, but if he just wants what he said then this is not necessary.
Salgar
When reference is made to "Foo" and "Bar", the OP usually wants a generic solution, not how to look for "Bar".
Philippe Leybaert
I realise that, but Dav's answer will suffice and is more readable to a larger proportion of the general programming population who are not regular expression experts.
Salgar
+1  A: 

Just search for "Bar".

For example in Groovy:

if("Foo(Bar)" =~ /Bar/) {
    println "match"
}

Will print 'match'

Gregory Mostizky
I think the assumption was that Foo and Bar were placeholder text that could vary.
Amber
Yeah that question is not really clear when I think about it
Gregory Mostizky
Personally, I think this is the best answer to the question as stated - match "Bar" within the string "Foo(Bar)" with a regex.
Dominic Rodger
+1  A: 

Should be enough:

\(.*\)

In Java the code would be:

  String foo = "Foo(Bar)";
  Pattern pattern = Pattern.compile("\(.*\)");
  Matcher matcher = pattern.matcher(foo);
  while (matcher.find()) {
            int beginIndex=matcher.start();
            int endIndex=matcher.end();
            return foo.substring(beginIndex, endIndex);
ungarida
A: 

You are omitting quite a bit of information: no platform or language used, no indications about the types of text you receive (i.e. is "Foo" static or can it change? Is "Bar" static? etc.).

Picking Ruby and assuming that "Foo" is stable, you can do this:

$ ruby -e 'p "Foo(Bar)"[/Foo\(([^)]*)\)/, 1]'
"Bar"
$
Robert Klemme
Thanks Dominic!
Robert Klemme
@Robert - np :)
Dominic Rodger