【问题标题】:How to get a value attribute from a hidden field using regex?如何使用正则表达式从隐藏字段中获取值属性?
【发布时间】:2014-03-15 05:06:15
【问题描述】:

我正在尝试解析一个 html 片段以检索我需要的一些数据。我试图在 SO 找到这里,但如果您按某些东西过滤并得到其他东西,则找不到解决方案。

我不需要解决方案来获取所有 html 标记或清除整个页面。我只是想改进我已经可以使用的Regex。

页面有 200 行长,我真的很想在隐藏字段上检索(为了更易读而中断行):

<!-- ...long list of html tags and hidden fields... -->

<input type="hidden" 
   name="javax.faces.ViewState" 
   id="javax.faces.ViewState" 
   value="valueIwant" 
   autocomplete="off" />

<!-- ...more html... -->

我需要通过 name 或 id 从这个名为 javax.faces.ViewState 的元素中检索 value 属性。

我最终得到了这个代码:

string value = Regex.Match(html, "<input[^>]*name=\"(javax.faces.ViewState)\"[^>]*>");

这会成功找到确切的标签,但会完全重新检索它。我真正想要的是改进这个Regex 只返回value 属性的内容。

我不想通过拨打Substring 来解决这个问题,因为我不知道该内容的确切大小。

【问题讨论】:

标签: c# regex


【解决方案1】:
Match match = Regex.Match(html, "<input[^>]*name=\"javax.faces.ViewState\"[^>]*value=\"([^\"]*)\"");
if (match.Success)
{
    Console.WriteLine(match.Groups[1].Value);
}

1) 如果name 和value 的顺序发生变化,这将不起作用。
2) 如果在 html 源代码中将双引号替换为单引号,这将不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2013-08-18
    • 1970-01-01
    相关资源
    最近更新 更多