Skip to main content
 首页 » 编程设计

c#正则表达式问题

2024年01月29日26sky-heaven

我想像这样在行中搜索一个值

<p align="center"><input type="hidden" name="e79e7ec" value="15302f565b"> 

我需要 name=""value 和 value=""value :P 创建这段代码,但是这段代码不起作用

Regex rloginRand = new Regex(@"<p align=center><input type=hidden name=\w*"); 
            Match mloginRand = rloginRand.Match(source); 
            string loginrand = ""; 
            if (mloginRand.Success) 
            { 
                 loginrand = mloginRand.ToString().Replace("<p align=center><input type=hidden name=", ""); 
            } 
            string loginrnd = ""; 
            Regex rloginRnd = new Regex(@"name="+ loginrand+"value=\w*"); 
            Match mloginRnd = rloginRnd.Match(source); 
 
            if (mloginRand.Success) 
            { 
                loginrnd = mloginRnd.ToString().Replace("name="+loginrand+" value=", ""); 
            } 

错误是

Form1.cs(71,69):错误 CS1009:无法识别的转义序列

在这一行

正则表达式 rloginRnd = new Regex(@"name="+ loginrand+"***value=\w****");

请您参考如下方法:

正则表达式并不总是 HTML 的最佳工具;我会使用 HTML Agility Pack (因为它不是 xhtml)和 xpath - 那么它应该非常简单:

    HtmlDocument doc = new HtmlDocument(); 
    doc.LoadHtml(html); 
    HtmlNode node = doc.DocumentNode.SelectSingleNode("input"); 
    // read (if you want) 
    string name = node.GetAttributeValue("name", ""), 
        value = node.GetAttributeValue("value", ""); 
    // wipe 
    node.SetAttributeValue("name", loginrand); 
    node.SetAttributeValue("value", ""); 
    // get html 
    html = doc.DocumentNode.OuterHtml;