Home > front end >  How would I select the first line from a block of code using regex?
How would I select the first line from a block of code using regex?

Time:02-01

I am trying to select the first line from a block of code (essentially a long string) using java. I am currently doing this using plain java but this seems clumsy. I would like to try and do this with regex instead if possible.

My code currently looks like:

int firstSpace = code.indexOf("package ");
String pac = code.substring(firstSpace);
pac = pac.replace("package ", "");
int endOfPac = pac.indexOf('\n');
pac = pac.substring(0,endOfPac);
String codeExpr = "result=data."   pac.trim()   ".resultObject";

The code string looks like:

String code = "package pac.regoFile\n some code"

The final result of codeExpr I need is:

result=data.pac.regoFile.resultObject

CodePudding user response:

You can use Pattern and Matcher to achieve this. Based on your input str, below can be used.

        Pattern p = Pattern.compile("^package (.*)?");
        Matcher m = p.matcher(code);
        if( m.find() ) {
            String pkg = m.group(1);
            String codeExpr = "result=data."   pkg.trim()   ".resultObject";
        }
  •  Tags:  
  • Related