如何使用Regex在动态字符串中查找值?

时间:2012-09-03 11:43:09

标签: c# asp.net regex

以下是可以动态构建的字符串示例。

{Static String} <a href="{Dynamic Value}"><b>{Dynamic Value 2}</b></a>

example of static text <a href="http://www.exampleurl.com">example value</a>

如何在C#中使用Regex查找{Dynamic Value 2}或示例值?

4 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

using System.Text.RegularExpressions;

private string ExtractString(string sourceString)
{
    // (?<=string) is positive look-behind where you search for string before the match.
    // .* is all characters in between.
    // (?=string) is positive look-ahead where you search for string after the match.
    string pattern = "(?<=<a.*?>).*(?=</a)";
    Match match = Regex.Match(sourceString, pattern);
    return match.Value;
}

当然,您应该实现某种异常处理机制。

请注意,这将返回

<b>{Dynamic Value 2}</b>

如果解析

<a href="{Dynamic Value}"><b>{Dynamic Value 2}</b></a>

如果需要,您可以使用其他正则表达式进一步处理字符串。

答案 1 :(得分:0)

试试这个,你会得到你想要的结果。

string Actualstring = "{static string}<a href='{Dynamic Value}'><b>{Dynamic Value 2}</b></a>"  string prevSplitBy = {static string};string desiredstring="";
     string FirstSplitBy = "<b>";
                    string SecondSplitBy = "</b>";
                    Regex regexprevSplit = new Regex(prevSplitBy );Regex regexFirstSplit = new Regex(FirstSplitBy);
                    Regex regexSecondSplit = new Regex(SecondSplitBy);
                  string[] StringprevSplit = regexprevSplit.Split(Actualstring );string[] StringFirstSplit = regexFirstSplit.Split(StringprevSplit[1] );
                    string[] StringSecondSplit = regexSecondSplit.Split(StringFirstSplit[1]); if(StringSecondSplit!=null){ for(int i=0 ; i <StringSecondSplit.count-1;i++)desiredstring=desiredstring+StringSecondSplit[i] }

desiredstring将有您想要的字符串。

答案 2 :(得分:0)

选项1:原始解析。不推荐。

{Static String} <a href="{Dynamic Value}"><b>{Dynamic Value 2}</b></a>

很好地解析了像

这样的东西
Regex parser = new Regex(
 @"*?\<a href\=\""(?<value1>[^\""]*)\""\>\<b\>(?<value2>[^\<]*)\<\/b\>\<\/a\>");

选项2:XML解析。推荐使用。

XElement el = XElement.Parse("<a>your long html string to parse</a>").Element("a");
string v1 = el.Attribute("href").Value;
string v2 = el.Element("b").Value;

答案 3 :(得分:0)

stackoverflow上的人似乎建议http://htmlagilitypack.codeplex.com/解析html并从中提取值。它比使用正则表达式更具容错能力。如果使用正则表达式,则必须更改正则表达式,如果您搜索的字符串中有任何更改。