开发者

Regular expression to return word present in the 1st enclosed parentheses

开发者 https://www.devze.com 2023-01-19 09:43 出处:网络
Example: ((UINT32)((384UL*1024UL) - 1UL)) should ret开发者_Python百科urn \"UINT32\" (char)abcshould return \"char\".

Example:

  1. ((UINT32)((384UL*1024UL) - 1UL)) should ret开发者_Python百科urn "UINT32"
  2. (char)abc should return "char".
  3. ((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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号