标记之间的文本<pre>在使用正则表达式 Java 时不保留换行符



这是我的问题。

String pattern1 = "<pre.*?>(.+?)</pre>";
Matcher m = Pattern.compile(pattern1).matcher(html);
if(m.find()) {
    String temp = m.group(1);
    System.out.println(temp);
}

temp不保留换行符…它像一条线一样流动。如何保持换行在临时?

你不应该用正则表达式解析HTML,但要解决这个问题,可以使用dotall修饰符…

String pattern1 = "(?s)<pre[^>]*>(.+?)</pre>";
                   ↑↑↑↑
                     |_______ Forces the . to span across newline sequences.

使用JSoup: html解析器

众所周知,你不应该使用正则表达式来解析html内容,你应该使用html解析器来代替。您可以在下面看到如何使用JSoup:

String html = "<p>lorem ipsum</p><pre>Hello World</pre><p>dolor sit amet</p>";
Document document = Jsoup.parse(html);
Elements pres = document.select("pre");
for (Element pre : pres) {
    System.out.println(pre.text());
}

模式。DOTALL:单行编译标志

然而,如果你仍然想使用正则表达式,记住点它是一个通配符,不匹配n,除非你故意指定它,所以你可以通过不同的方式实现这一点,比如使用Pattern.DOTALL

String pattern1 = "<pre.*?>(.+?)</pre>";
Matcher m = Pattern.compile(pattern1, Pattern.DOTALL).matcher(html);
if(m.find()) {
    String temp = m.group(1);
    System.out.println(temp);
}

内联单行标志:

或者像这样在正则表达式中使用s标志:

String pattern1 = "(?s)<pre.*?>(.+?)</pre>";
Matcher m = Pattern.compile(pattern1).matcher(html);
if(m.find()) {
    String temp = m.group(1);
    System.out.println(temp);
}

Regex技巧

或者你也可以使用一个正则表达式技巧,包括使用互补集,如[sS], [dD], [wW]等。这样的:

String pattern1 = "<pre.*?>([\s\S]+?)</pre>";
Matcher m = Pattern.compile(pattern1).matcher(html);
if(m.find()) {
    String temp = m.group(1);
    System.out.println(temp);
}

但是正如nhahtdh在他的评论中指出的,这个技巧可能会影响regex引擎的性能。

最新更新