use regex pattern matching to remove the two leading and trailing lines

You may use this regex to remove first 2 and last 2 lines:

String code = sampleCode.replaceAll("^([^\n]*\n){2}|([^\n]*\n){2}$", "");

RegEx Demo

  • ^([^\n]*\n){2} matches first 2 lines of string
  • ([^\n]*\n){2}$ matches last 2 lines of string

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top