【问题标题】:Extract all string data except String containing HTML Table's in java在java中提取除包含HTML表格的字符串之外的所有字符串数据
【发布时间】:2020-08-28 14:20:35
【问题描述】:

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

<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 表之前和之后提取整个字符串。并添加“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>

【问题讨论】:

  • 由于堆栈溢出限制,我已经从 HTML 表的字符串中删除了相当多的内容。

标签: java string string-matching


【解决方案1】:

您可以通过 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>

【讨论】:

    【解决方案2】:

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

        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 字符串的大小。

    这只是一种尝试的方法。

    【讨论】:

    • 谢谢! “正则表达式评估是 CPU 密集型的,具体取决于您的 HTML 字符串的大小。”。那么它的复杂性呢? @克劳斯
    • @Sam 阅读此处stackoverflow.com/questions/5892115/…。这实际上取决于输入的大小。就像,有人可以提供一个足够大的输入,以消耗 cpu 来评估正则表达式的输入
    猜你喜欢
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    相关资源
    最近更新 更多