簡體   English   中英

如何在C#上獲取字符串的中心部分

[英]How to get the center part of string on C#

我只需要使用C#就可以使用Rocky44的中心字符串

Hi <a href="http://example.com/index.php?action=profile"><span>Rocky44</span></a>

我嘗試了一些拆分方法,但無法正常工作

string[] result = temp.Split(new string[] { "<a href=" + "http://example.com/index.php?action=profile" + "><span>" , "</span></a>" }, StringSplitOptions.RemoveEmptyEntries); 

例:

Hi <a href="http://example.com/index.php?action=profile"><span>Rocky44</span></a>

至:

Rocky44

使用HTML解析器。 我將舉一個使用HtmlAgilityPack的例子

string html = @"Hi <a href=""http://example.com/index.php?action=profile""><span>Rocky44</span></a>";
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var text = doc.DocumentNode.SelectSingleNode("//span").InnerText;

您走在正確的軌道上; 您只是沒有正確地將引號轉義:

string[] result = temp.Split(new string[] { "<a href=\"http://example.com/index.php?action=profile\"><span>" , "</span></a>" }, StringSplitOptions.RemoveEmptyEntries);

當然,這是假設您的輸入將始終采用給定的格式。 正如I4V所提到的,如果您嘗試做更復雜的事情,則HTML解析器可能會派上用場。

使用IndexOf方法找到<span></span>的索引。

然后(調整<span>的長度)使用String.Substring方法獲取所需的文本。

string FindLinkText(string linkHtml)
{
    int startIndex = linkHtml.IndexOf("<span>") + "<span>".Length,
        length = linkHtml.IndexOf("</span>") - startIndex;

    return linkHtml.Substring(startIndex, length);
}

如果您只打算得到這種東西(例如這種 HTML),那么我將使用正則表達式。 否則, 請勿使用它

string HTML = @"Hi <a href="http://example.com/index.php?action=profile"><span>Rocky44</span></a>"
var result = Regex.Match(HTML, @".*<a.*><span.*>(.*)</span></a>").Groups[1].Value;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM