有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多行上的java正则表达式

我有以下代码:

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

其中缓冲区为:

  <tag 1>

     My Value

  </tag 1>

如何为正则表达式启用多行匹配,以便匹配此缓冲区?谢谢


共 (1) 个答案

  1. # 1 楼答案

    为了使点匹配换行符,您需要使用DOTALL标志:

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

    否则:

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

    但我要提醒大家,使用正则表达式解析HTML/XML并不是最好的主意