如何使用正则表达式提取正文内容

far*_*oft 6 html javascript regex

我在var中有这个代码.

<html>

    <head>
        .
        .
        anything
        .
        .
    </head>

    <body anything="">
        content
    </body>

</html>
Run Code Online (Sandbox Code Playgroud)

要么

<html>

    <head>
        .
        .
        anything
        .
        .
    </head>

    <body>
        content
    </body>

</html>
Run Code Online (Sandbox Code Playgroud)

结果应该是

content
Run Code Online (Sandbox Code Playgroud)

Jef*_*ake 20

请注意,上面提供的基于字符串的答案在大多数情况下都适用.正则表达式解决方案提供的一个主要优势是,您可以更轻松地在打开/关闭正文标记上提供不区分大小写的匹配.如果您不关心这一点,那么在这里使用正则表达式没有重要理由.

对于那些将HTML和正则表达式放在一起并投入合适的人......由于您实际上并未尝试使用此解析HTML,因此您可以使用正则表达式执行此操作.如果,由于某种原因,content包含</body>然后它会失败,但除此之外,你有一个足够具体的场景,正则表达式能够做你想要的:

const strVal = yourStringValue; //obviously, this line can be omitted - just assign your string to the name strVal or put your string var in the pattern.exec call below 
const pattern = /<body[^>]*>((.|[\n\r])*)<\/body>/im;
const array_matches = pattern.exec(strVal);
Run Code Online (Sandbox Code Playgroud)

完成上述操作后,array_matches[1]将保存<body</body>标签之间的任何内容.

  • @Doug尝试在较高层次上解析HTML与尝试提取单个标记的特定内容之间存在巨大差异。特别是问题和答案均指示的标签在所有原始资料中仅出现一次。 (2认同)

Dou*_*oug -3

我相信你可以将你的html文档加载到.net HTMLDocument对象中,然后简单地调用HTMLDocument.body.innerHTML?

我确信使用较新的 XDocumnet 也有更简单的方法。

只是为了回应上面的一些评论,正则表达式并不是最好的工具,因为 html 不是常规语言,并且存在一些难以解决的边缘情况。

https://en.wikipedia.org/wiki/Regular_language

享受!