user2320462
user2320462

Reputation: 269

Regex over multiple lines

I have the following code:

  Matcher matcher = Pattern.compile("<tag 1>(.*?)</tag 1>").matcher(buffer);
  int nr = 0;
  while (matcher.find()) {
         System.out.println("Match no. " + ++nr + ": '" + matcher.group() + "'");
  }

Where buffer is:

  <tag 1>

     My Value

  </tag 1>

How can I enable multiline match for my regex, so I can match this buffer? Thanks!

Upvotes: 2

Views: 83

Answers (1)

anubhava
anubhava

Reputation: 786329

You need to use DOTALL flag in order to make DOT match newlines:

Matcher matcher = Pattern.compile("(?s)<tag 1>(.*?)</tag 1>").matcher(buffer);

OR else:

Matcher matcher = Pattern.compile("<tag 1>(.*?)</tag 1>", Pattern.DOTALL)

But let me caution that parsing HTML/XML using regex is not the greatest idea.

Upvotes: 2

Related Questions