繁体   English   中英

在C#中使用正则表达式来自字符串的特定值

[英]Particular value from a string using regex in c#

我需要从给定的string中提取$ value。

string text = "<h2 class="knownclass unknownclass1 unknownclass2" title="Example title>$Value </h2>"

使用代码-:

Match m2 = Regex.Match(text, @"<h2 class=""knownclass(.*)</h2>", RegexOptions.IgnoreCase);

它为我提供了完整的值-:unknownclass1 unknownclass2“ title =”示例title> $ Value。但是我只需要$ value部分。 请告诉我。谢谢。

假设字符串始终遵循这种格式,请考虑以下代码:

var index = text.IndexOf(">");
text.Substring(index + 1, text.IndexOf("<", index));

正如多次提到的那样,使用Regex解析HTML或XML是不好的。 忽略这一点,您捕获了太多东西。 这是应该起作用的替代正则表达式。

@"<h2 class=""knownclass[^""]*"">(.*)</h2>"

如果其字符串的模式始终相同,则可以考虑以下情况:

string text = "<h2 class=\"knownclass unknownclass1 unknownclass2\" title=\"Example title>$Value </h2>";
string result = "";

Regex test = new Regex(@"\<.*?\>(.*?)\</h2\>");
MatchCollection matchlist = test.Matches(text);

if (matchlist.Count > 0)
{
    for (int i = 0; i < matchlist.Count; i++)
    {
        result = matchlist[i].Groups[1].ToString();
    }
}

但是,如果您使用的是XML文件或HTML文件,建议您将XmlTextReader用于XML,将HtmlAgilityPack用于HTML

http://msdn.microsoft.com/zh-CN/library/system.xml.xmltextreader.aspx

http://htmlagilitypack.codeplex.com/

希望能帮助到你!

暂无
暂无

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

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