提取除包含 HTML Table 的 java 中的字符串之外的所有字符串数据

Extract all string data except String containing HTML Table's in java

我有一个像这样的长字符串。

<p>Some Text above the tabular data. I hope this text will be seen.</p>

<table border="1" cellpadding="0" cellspacing="0">
    <tbody>
        <tr>
            <td style="width:150px">
            <p>S.No.</p>
            </td>



            </td>
        </tr>
        <tr>
            <td style="width:150px">
            <p>2</p>
            </td>


    </tbody>
</table>

<p>&nbsp;</p>

<p>Please go through this tabular data.</p>

<table border="1" cellpadding="0" cellspacing="0">
    <tbody>
        <tr>
            <td style="width:150px">
            <p>S.No.</p>
            </td>


        </tr>
        <tr>
            <td style="width:150px">
            <p>1</p>
            </td>


        <tr>
            <td style="width:150px">
            >
            </td>

            </td>
        </tr>
    </tbody>
</table>


<p>End Of String</p>

现在我想像这样提取 html table 之前和之后的整个字符串。并添加 "HTML Table..." 代替 HTML Table。我尝试了几件事,但无法实现。尝试拆分成数组,但没有用

示例输出

<p>Some Text above the tabular data. I hope this text will be seen.</p>

<p>&nbsp;</p>
HTML Table.... 
<p>Please go through this tabular data.</p>


<p>End Of String</p>

您可以简单地通过 String.replaceAll 使用正则表达式处理多行和不区分大小写的标志 (?is):

String noTables = longTableString.replaceAll("(?is)(\<table .*?\</table\>)", "HTML Table...");
// result
<p>Some Text above the tabular data. I hope this text will be seen.</p>

HTML Table...

<p>&nbsp;</p>

<p>Please go through this tabular data.</p>

HTML Table...


<p>End Of String</p>

这可能不是最优雅的解决方案,您可以先使用正则表达式捕获您的 table 位置,然后将其替换为所需的内容。像下面这样的东西会有所帮助。

    String htmlString = <your html string> ;        
    Pattern pattern = Pattern.compile( "(<table)([\s\S]*?)(</table>)" ); // capture table elements using a suitable regex.
    Matcher matcher = pattern.matcher( htmlStr );
    String result = htmlStr;
    while( matcher.find() )
    {
        // replace the table elements with another string 
        result = result.replace( htmlStr.substring( matcher.start(), matcher.end() ), "HTML Table...." );
    }
    System.out.println( result ); // print output

这种方法有一些缺点,例如您的正则表达式必须与 html 内容匹配。并且间距取决于原始字符串空格。您真的无法控制输出中空格的外观。更重要的是,正则表达式评估 CPU 密集取决于 HTML 字符串的大小。

这只是一种尝试方法。