繁体   English   中英

C# 拆分并获取值

[英]C# Split and get value

我在从 webbrowser.document 获取项目时遇到了一些问题。

我需要的文档中的代码部分是这个>

primary-text,7.gm2-body-2">**ineedthis.se**</div> <div jstcache="194" 

我需要解析每次都不同的“ineedthis.se”。

我的代码是这样的

if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
                {
                   System.IO.StreamReader sr = new System.IO.StreamReader(webBrowser1.DocumentStream.ToString());
                    string rssourcecode = sr.ReadToEnd();
                     Regex r = new Regex("7.gm2-body-2 > </ div > < div ", RegexOptions.Multiline);
                    MatchCollection matches = r.Matches(rssourcecode);
                    // Dim r As New System.Text.RegularExpressions.Regex("here need splitersorsomething", RegexOptions.Multiline)
                    foreach (Match itemcode in matches)
                    {
                        listBox1.Items.Add(itemcode.Value.Split(here need splites).GetValue(2));
                    }
                   
                }

所以。 你能帮我用正确的分离器吗? 多谢

您的问题不是很清楚,但我仍然可以理解的是您想从字符串中获取字符串(子字符串)的一部分。

假设你有一个保存在变量中的字符串值:

string stringValue = primary-text,7.gm2-body-2">**ineedthis.se**</div> <div jstcache="194";

而你要提取的是: ineedthis.se

所以你可以试试stringValue.Substring(31,44); .

您可以参考: https : //www.c-sharpcorner.com/UploadFile/mahesh/substring-in-C-Sharp/

假设您的字符串如下

var str = "<div primary-text,7.gm2-body-2\">**some random text**</div> <div jstcache=\"194\""; 

以下是一个非常基本的解决方案,但会帮助您回答

var foundStart = false;
var foundEnd = false;
var startIndex = -1;
var length = 0;
for(var index = 0; index < str.Length; index++)
{
    if (!foundStart)
    {
        if (str[index].Equals('<') && str.Substring(index, 4).Equals("<div"))
        {
            foundStart = true;                  
            continue;
        }
    }

    if (foundStart && !foundEnd)
    {
        if (str[index].Equals('>'))
        {
            foundEnd = true;
            continue;
        }
    }

    if (foundStart && foundEnd)
    {   
        if (startIndex == -1)
            startIndex = index;
        else
            length++;
            
        if (str[index + 1].Equals('<'))
        {
            foundStart = false;
            foundEnd = false;
            break;
        }
    }
}

//// This is your answer
Console.WriteLine(str.Substring(startIndex, length));

暂无
暂无

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

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