繁体   English   中英

Regex.Match参数可能吗?

[英]Regex.Match Parameter Possible?

美好的一天,

我有一些HTML输入,我想执行搜索和替换操作。

string html = @"
    <div class=""left bottom-margin"">
    <input id=""0086"" maxlength=""29"" data-src=""200:80"" type=""text""><br />
    <input id=""0087"" maxlength=""38"" data-src=""201:80"" type=""text""><br />
    <input id=""0088"" maxlength=""38"" data-src=""202:80"" type=""text""><br />
</div>";    

// Here we call Regex.Match.
Match match = Regex.Match(html, @"(<input.*id=""0087"".*?>)", RegexOptions.IgnoreCase);

// Here we check the Match instance.
if (match.Success)
{
    // Finally, we get the Group value and display it.
    string key = match.Groups[1].Value;
    Console.WriteLine(key);
} else {
    Console.WriteLine("No Match...");
}

到目前为止,这段代码确实有效,但是我希望能够为Regex.Match初始化提供一个参数。 这可能吗? 如果我想搜索0086或0088作为ID怎么办? 我有几百个这样的标签,我想通过提供一个参数来找到HTML标签?

我知道@会使字符串保持原状。

但是我尝试这样做:

// string pattern = "(<input.*id=\"\"0087\"\".*?>)";
// string pattern = "(<input.*id=\"\"" + "0087" + "\"\".*?>)";

这也不起作用。 我见过的大多数Regex.Match示例都使用@ verbatim符号进行实际匹配。 我对此的理解正确吗?

有什么建议么?

您不能为正则表达式提供参数。 但是您可以...不尝试将正则表达式强制成为HTML解析器。

  • 如果您的文档包含有效的标记,则可以将其加载到合适的XMLDocument中,并以多种不同方式之一应用所需的转换:
    • 使用XPATH查询以编程方式
    • 通过遍历文档以找到您感兴趣的节点,
    • 应用XSLT转换。
    • 使用Linq for XML
  • 或者,您可以通过NuGet安装HTML Agility Pack ,将文档加载到HTmlDocument并使用其转换功能。

如果确定要使用正则表达式,则可以

  • 动态生成正则表达式,例如

     Regex ConstructRegex( int id ) { string pattern = string.format( @"(<input.*id=""{0:0000}"".*?>)" , id ) ; Regex instance = new Regex( pattern ) ; return instance } 
  • 使您的正则表达式通用,并提供MatchEvaluator / Func<Match,string>将所需的转换应用于每个匹配项(如果需要):

     static readonly Regex rx = new Regex( @"(<input.*id=""(?<id>\\d\\d\\d\\d)"".*?>)" ) ; string Transform( string html , Func<string,string> transform ) { string transformed = rx.Replace( html, transform ) ; return transformed ; } 

    您可以这样使用:

     string raw = "some html here" ; string cooked = Transform( raw , m => { int id = int.Parse( m.Groups["id"].Value ) ; string s = Match.Value ; if ( id == 86 ) { s = apply_some_transformation_here(m.Value) ; } return s ; }) ; 

这个怎么样:

string pattern = String.Format(@"(<input.*id=""{0}"".*?>)", "0087");

看起来对我来说很好。

实际上,即使这样也可以:

string pattern = @"(<input.*id=""" + "0087" + @""".*?>)";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM