我正在尝试解析 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
来解决这个问题,因为我不知道这个内容的确切大小。
最佳答案
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 源中将双引号替换为单引号,这将不起作用。
关于c# - 如何使用正则表达式从隐藏字段中获取值属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22415577/