Regular expression to return word present in the 1st enclosed parentheses
Example:
((UINT32)((384UL*1024UL) - 1UL))
should ret开发者_Python百科urn "UINT32"(char)abc
should return "char".((int)xyz)
should return "int".
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);
Pattern p = Pattern.compile("\\(([^\\(\\)]+?)\\)");
Matcher m = p.matcher(input);
if (m.find())
result = m.group(1);
精彩评论