在c#.net字符串中包含很少的段落,如<p> </p>,但我想要第一段子字符串,我怎么能得到它

时间:2013-11-29 09:50:34

标签: c#

//  Extract News List for SectionID Received;
String sSQL = "SELECT *, DATE_FORMAT(NW_MakerDate, '%d %M %Y') as                     MakerDate";
sSQL = sSQL + " FROM bhavnagari.news_master";
sSQL = sSQL + " WHERE NW_Section = '" + lblSectionID.Text.ToString() +                  "'";
sSQL = sSQL + " ORDER BY Nw_SerialNo DESC";

DataSet DS1 = new DataSet();
OdbcDataAdapter da = new OdbcDataAdapter(sSQL,conn);
da.Fill(DS1);

if (DS1.Tables["table"].Rows.Count > 0)
{
    str1 = DS1.Tables["table"].Rows[0]["Nw_Detail"].ToString();

    str3 = str1.Replace("<p>", "");
    str3 = str3.Replace("</p>", " ");

    String[] str3 = str3.Split(' ');

    for (int i = 0; i < 1; i++)
    {
        News_DetailIntro = str3[i];

    }

}

在上面的代码中,有一个包含段落的字符串。我想从这个字符串中只获取第一段。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

试试这个功能,

private string GetFirstParagraph(string yourHtmltext)
    {
        Match m = Regex.Match(yourHtmltext, @"<p>\s*(.+?)\s*</p>");
        if (m.Success)
        {
            return m.Groups[1].Value;
        }
        else
        {
            return yourHtmltext;
        }
    }

答案 1 :(得分:0)

试试这个:

     String str1 = "/*your data*/";
     int index1=str1.IndexOf("<p>");
     int index2=str1.IndexOf("</p>");

     if(index1!=-1 && index2!=-1)
     String finalStr=str1.Substring(index1+3,index2-3));