0

I have the following pattern contained n times in a file:

ENUM CMF_QUOTE_EVENT
    CMF_QUOTE_EVENT_Activate            "Activate"
    CMF_QUOTE_EVENT_Suspend             "Suspend"
    CMF_QUOTE_EVENT_Delete              "Delete"
ENDENUM

My goal is to catch all the values of the enum. Basically I need the three lines between the keywords "ENUM" and "ENDENUM".

I tried to use a Multiline Regex for that but I still can't catch it. Here's I did it:

  BufferedReader br = new BufferedReader(new FileReader(file));
  String line = "";
  StringBuilder sb = new StringBuilder();    

  while ((line = br.readLine()) != null)
  {
      sb.append(line.replace("\\s",""); // delete tabs and ws
  }

  Pattern pattern= Pattern.compile("ENUM(.*)(.|\\s)*ENDENUM", Pattern.MULTILINE);
  Matcher match = pattern.matcher(sb.toString());
  while (match.find())
  {
      // do something
  }    
  br.close();

I am wondering using a grammar instead, but it looks very heavy for this only use. Can I do this kind of thing with a regex?

Thank you all

Amaury
  • 9
  • 1

1 Answers1

0

If you check the documentation:

By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input. When in MULTILINE mode $ matches just before a line terminator or the end of the input sequence.

So, multiline flag is not to capture multiple lines but to modify anchors behavior.

What you want to use is to capture multiple lines, so you need to modify . behavior. For doing this you have to use the Pattern.DOTALL flag

Pattern pattern = Pattern.compile("ENUM(.*?)ENDENUM", Pattern.DOTALL);

Working demo

And you have to grab the content from the capturing group 1:

Matcher match = pattern.matcher(sb.toString());
while (match.find())
{
    // do something
    String enumContent = match.group(1);
} 
Federico Piazza
  • 30,085
  • 15
  • 87
  • 123