I'm trying to get a substring from a block of text that can contain new lines. Whats the regex needed to capture everything including newlines between 2 strings thats are passed in?

The regex below works in a similar function that doesn't need to include new lines.

private static String getSubString(
    String text,
    String startString,
    String endString
  ) {
    List<String> matchList = new List<String>();
    String patternStart = Pattern.quote(startString);
    String patternEnd = Pattern.quote(endString);
    Pattern pattern = Pattern.compile(patternStart + '(.*?)' + patternEnd);
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {

    if (matchList.size() > 0) {
      return matchList[0];

    return '';

1 Answer 1


I believe you simply need to set the single-line flag (s) which will make dot match newline characters.

Pattern.compile('(?s)' + patternStart + '(.*?)' + 'patternEnd')

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .