tags:

views:

59

answers:

2

Example:

  1. ((UINT32)((384UL*1024UL) - 1UL)) should return "UINT32"
  2. (char)abc should return "char".
  3. ((int)xyz) should return "int".
+4  A: 
    Pattern p = Pattern.compile("\\(([^()]*)\\)");
    String[] tests = {
            "((UINT32)((384UL*1024UL) - 1UL))",
            "(char)abc",
            "((int)xyz)"
    };

    for (String s : tests) {
        Matcher m = p.matcher(s);
        if (m.find())
            System.out.println(m.group(1));
    }

Prints

UINT32
char
int

Explanation of the regular expression:

  • \\( Start with a (
  • ( start capturing group
  • [^()]* anything but ( and ) 0 or more times
  • ) end capturing group
  • \\) end with a ).

Using regular expressions is a bit of an overkill though. You could also do

int close = s.indexOf(')');
int open = s.lastIndexOf('(', close);
result = s.substring(open+1, close);
aioobe
u are right(4 to go)
org.life.java
Sorry to say but Its not working for (char)abc
It is for me... For me the code snippet prints the three lines below. Thus, the second test `(char)abc` results in `char`, which is the expected result, no? See http://ideone.com/pEoyg
aioobe
So thankful to you.But its not working for following case
case 1: (int)10case 2: (int)(10)case 3: (long)(100000)(10)
It doesn't? Have a look at http://ideone.com/5mSC9 Which case is wrong?
aioobe
@aioobe: Why not put the closing paren in the character class as well? Then you wouldn't need the reluctant quantifier: `[^()]*`
Alan Moore
I had that at first, but with escapes on the `)` it was one more character :-) But from your comment I recall that escapes is not needed in character-classes, so I'll update :-)
aioobe
Thanks For your great support.Its working fine.There was fault in my program itself.
A: 
Pattern p = Pattern.compile("\\(([^\\(\\)]+?)\\)");
Matcher m = p.matcher(input);
if (m.find())
  result = m.group(1);
Andreas_D
you may want to have `*` instead of `+?` in order to be able to handle a first enclosed parenthesis that is empty.
aioobe
Wonderful!!!!.....Can u please explain me it?
Sorry to say but Its not working for (char)abc