javaregexannotationstext-processing

Get Java annotation's desired data


I get the following String response when I pull the annotations of a method in Java class:

@client.test.annotations.TestInfo(id=[C10137])
@org.testng.annotations.Test(alwaysRun=false, expectedExceptions=[]..

However I am only interested in the id=[C10137] part and want to get that number - 10137. There can also be a case as:

CASE1: //multiple ids

@client.test.annotations.TestInfo(id=[C10137, C12121])
    @org.testng.annotations.Test(alwaysRun=true,...

CASE2: //no id

@client.test.annotations.TestInfo(id=[]) //ignore this time
    @org.testng.annotations.Test(alwaysRun=true,...

Will regex work for me here to produce this array of id's? OR some other good approach to get that desired id array.


Solution

  • You can use this regex

    \bid\b=\[(.+?)\]
    

    Regex Demo

    Java Code

    String line = "@client.test.annotations.TestInfo(id=[C10137])@org.testng.annotations.Test(alwaysRun=false, expectedExceptions=[].."; 
    String pattern = "\\bid\\b=\\[(.+?)\\]";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(line);
    
    if (m.find()) {
        System.out.println(m.group(1));
    }
    

    Ideone Demo