如何使用 RegEx 从 HTML 中提取值?

发布于 2024-10-22 00:43:29 字数 2128 浏览 1 评论 0原文

给定以下 HTML:

<p><span class="xn-location">OAK RIDGE, N.J.</span>, <span class="xn-chron">March 16, 2011</span> /PRNewswire/ -- Lakeland Bancorp, Inc. (Nasdaq:   <a href='http://studio-5.financialcontent.com/prnews?Page=Quote&Ticker=LBAI' target='_blank' title='LBAI'> LBAI</a>), the holding company for Lakeland Bank, today announced that it redeemed <span class="xn-money">$20 million</span> of the Company's outstanding <span class="xn-money">$39 million</span> in Fixed Rate Cumulative Perpetual Preferred Stock, Series A that was issued to the U.S. Department of the Treasury under the Capital Purchase Program on <span class="xn-chron">February 6, 2009</span>, thereby reducing Treasury's investment in the Preferred Stock to <span class="xn-money">$19 million</span>. The Company paid approximately <span class="xn-money">$20.1 million</span> to the Treasury to repurchase the Preferred Stock, which included payment for accrued and unpaid dividends for the shares. &#160;This second repayment, or redemption, of Preferred Stock will result in annualized savings of <span class="xn-money">$1.2 million</span> due to the elimination of the associated preferred dividends and related discount accretion. &#160;A one-time, non-cash charge of <span class="xn-money">$745 thousand</span> will be incurred in the first quarter of 2011 due to the acceleration of the Preferred Stock discount accretion. &#160;The warrant previously issued to the Treasury to purchase 997,049 shares of common stock at an exercise price of <span class="xn-money">$8.88</span>, adjusted for stock dividends and subject to further anti-dilution adjustments, will remain outstanding.</p>

我想获取 元素内的值。我还想获取 元素上的 class 属性的值。

理想情况下,我可以通过函数运行一些 HTML 并返回提取实体的字典(基于上面定义的 解析)。

上面的代码是来自一个较大的 HTML 源文件的片段,它无法与 XML 解析器进行匹配。所以我正在寻找一个可能的正则表达式来帮助提取感兴趣的信息。

Given the following HTML:

<p><span class="xn-location">OAK RIDGE, N.J.</span>, <span class="xn-chron">March 16, 2011</span> /PRNewswire/ -- Lakeland Bancorp, Inc. (Nasdaq:   <a href='http://studio-5.financialcontent.com/prnews?Page=Quote&Ticker=LBAI' target='_blank' title='LBAI'> LBAI</a>), the holding company for Lakeland Bank, today announced that it redeemed <span class="xn-money">$20 million</span> of the Company's outstanding <span class="xn-money">$39 million</span> in Fixed Rate Cumulative Perpetual Preferred Stock, Series A that was issued to the U.S. Department of the Treasury under the Capital Purchase Program on <span class="xn-chron">February 6, 2009</span>, thereby reducing Treasury's investment in the Preferred Stock to <span class="xn-money">$19 million</span>. The Company paid approximately <span class="xn-money">$20.1 million</span> to the Treasury to repurchase the Preferred Stock, which included payment for accrued and unpaid dividends for the shares.  This second repayment, or redemption, of Preferred Stock will result in annualized savings of <span class="xn-money">$1.2 million</span> due to the elimination of the associated preferred dividends and related discount accretion.  A one-time, non-cash charge of <span class="xn-money">$745 thousand</span> will be incurred in the first quarter of 2011 due to the acceleration of the Preferred Stock discount accretion.  The warrant previously issued to the Treasury to purchase 997,049 shares of common stock at an exercise price of <span class="xn-money">$8.88</span>, adjusted for stock dividends and subject to further anti-dilution adjustments, will remain outstanding.</p>

I'd like to get the values inside the <span> elements. I'd also like to get the value of the class attribute on the <span> elements.

Ideally I could just run some HTML through a function and get back a dictionary of extracted entities (based on the <span> parsing defined above).

The above code is a snippet from a larger source HTML file, which fails to pare with an XML parser. So I'm looking for a possible regular expression to help extract the information of interest.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡看悲欢离合 2024-10-29 00:43:29

使用此工具(免费):
http://www.radsoftware.com.au/regexdesigner/

使用此正则表达式:

"<span[^>]*>(.*?)</span>"

第 1 组中的值(对于每场比赛)将是您需要的文本。

在 C# 中,它看起来像:

            Regex regex = new Regex("<span[^>]*>(.*?)</span>");
            string toMatch = "<span class=\"ajjsjs\">Some text</span>";
            if (regex.IsMatch(toMatch))
            {
                MatchCollection collection = regex.Matches(toMatch);
                foreach (Match m in collection)
                {
                    string val = m.Groups[1].Value;
                    //Do something with the value
                }
            }

修正回答评论:

            Regex regex = new Regex("<span class=\"(.*?)\">(.*?)</span>");
            string toMatch = "<span class=\"ajjsjs\">Some text</span>";
            if (regex.IsMatch(toMatch))
            {
                MatchCollection collection = regex.Matches(toMatch);
                foreach (Match m in collection)
                {
                    string class = m.Groups[1].Value;
                    string val = m.Groups[2].Value;
                    //Do something with the class and value
                }
            }

Use this tool (free):
http://www.radsoftware.com.au/regexdesigner/

Use this Regex:

"<span[^>]*>(.*?)</span>"

The values in Group 1 (for each match) will be the text that you need.

In C# it will look like:

            Regex regex = new Regex("<span[^>]*>(.*?)</span>");
            string toMatch = "<span class=\"ajjsjs\">Some text</span>";
            if (regex.IsMatch(toMatch))
            {
                MatchCollection collection = regex.Matches(toMatch);
                foreach (Match m in collection)
                {
                    string val = m.Groups[1].Value;
                    //Do something with the value
                }
            }

Ammended to answer comment:

            Regex regex = new Regex("<span class=\"(.*?)\">(.*?)</span>");
            string toMatch = "<span class=\"ajjsjs\">Some text</span>";
            if (regex.IsMatch(toMatch))
            {
                MatchCollection collection = regex.Matches(toMatch);
                foreach (Match m in collection)
                {
                    string class = m.Groups[1].Value;
                    string val = m.Groups[2].Value;
                    //Do something with the class and value
                }
            }
停顿的约定 2024-10-29 00:43:29

假设您没有嵌套 span 标签,则以下内容应该有效:

/]+class=\"(.*?)\"[^ >]*)?>(.*?)<\/span>/

我只对它做了一些基本测试,但它会匹配 span 标签的类(如果存在)直到标签关闭为止。

Assuming that you have no nested span tags, the following should work:

/<span(?:[^>]+class=\"(.*?)\"[^>]*)?>(.*?)<\/span>/

I only did some basic testing on it, but it'll match the class of the span tag (if it exists) along with the data until the tag is closed.

唯憾梦倾城 2024-10-29 00:43:29

强烈建议您使用真正的 HTML 或 XML 解析器来代替。 您无法使用正则表达式可靠地解析 HTML 或 XML ——你能做的最多就是接近,你越接近,你的正则表达式就会越复杂和耗时。如果您有一个大型 HTML 文件需要解析,则很可能会破坏任何简单的正则表达式模式。

]*>(.*?) 这样的正则表达式将适用于您的示例,但是有很多 XML 有效的代码很难甚至是不可能的使用正则表达式进行解析(例如, foo bar 将打破上述模式)。如果您想要一些可以在其他 HTML 示例上运行的东西,那么正则表达式不是您的最佳选择。

由于您的 HTML 代码不是 XML 有效的,因此请考虑使用 HTML Agility Pack ,我听说非常好。

I strongly advise you to use a real HTML or XML parser for this instead. You cannot reliably parse HTML or XML with regular expressions--the most you can do is come close, and the closer you get, the more convoluted and time-consuming your regex will be. If you have a large HTML file to parse, it's highly likely to break any simple regex pattern.

Regex like <span[^>]*>(.*?)</span> will work on your example, but there's a LOT of XML-valid code that's difficult or even impossible to parse with regex (for example, <span>foo <span>bar</span></span> will break the above pattern). If you want something that's going to work on other HTML samples, regex isn't the way to go here.

Since your HTML code isn't XML-valid, consider the HTML Agility Pack, which I've heard is very good.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文