0

I am using FileUtils from apache commons.io to search text between two strings in a file with the following code:

Pattern p = Pattern.compile(Pattern.quote(fromDate) + "(.*?)" + Pattern.quote(toDate));

try {
    Matcher m = p.matcher(fileContent);                  
    while (m.find()) {
        System.out.println(m.group(1));

But there is an error it is giving output only when both the strings lie in same line, no output if strings are in at different lines? Here i am taking the content of whole file into a Sting Varibale "fileContent".

ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
iymrahul
  • 94
  • 1
  • 1
  • 11

2 Answers2

0

The dot won't search over multiple lines. You need to give a second parameter for this Pattern.DOTALL like so: Pattern p = Pattern.compile(Pattern.quote(fromDate) + "(.*?)" + Pattern.quote(toDate), Pattern.DOTALL);

Also this topics has some good explanation how it works: Match multiline text using regular expression

Community
  • 1
  • 1
Albert Bos
  • 2,012
  • 1
  • 15
  • 26
0

try ending the regex with ?s so you new regex should be: "(.*?s)"

In most case the matcher stops evaluate expression when it encounters a line feed \n. ?s make the matcher pass the \n when it try to match the regex.

Sagi Forbes
  • 2,139
  • 2
  • 13
  • 16