在C#中拆分和剪切字符串

时间:2014-08-21 16:38:26

标签: c# string split

C#语言的新手。我有一个字符串,如下所示:

  Internet Protocol Version 4, Src: 192.168.1.204 (192.168.1.204), Dst: 162.159.242.165 (162.159.242.165)

其中包含两个数据:192.168.1.204和162.159.242.165。我正在努力理解如何将这两组数字输出并将它们放入不同的字符串中以便以后使用。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

你的字符串看起来像被,分隔的部分分解,所以我要做的第一件事就是把它分解成那些部分

string[] sections = str.Split(',');

IT看起来将这些部分分解为参数名称和参数值,它们由:分隔。所以我会迭代你的部分,并将其分解为名称和值

string name = sections[i].Split(':')[0];
string value = sections[i].Split(':')[1];

现在你的价值不仅仅是一个IP地址,所以你可以使用正则表达式来提取看起来像ip地址的第一件事

var address = Regex.Match(value, @"\d+\.\d+\.\d+\.\d+").Value;

您还可以使用name字符串来确定哪些部分代表Src,哪些部分代表Dst


现在要小心这个。我给你的正则表达式将匹配无效的IP,例如300.19028.38.1如果你害怕匹配非IP地址的东西,你可以比我更努力地获得更好的正则表达式。

此外,如果您的字符串中有额外的未激活的,:,则此逻辑将变为无效。

答案 1 :(得分:0)

以下是使用Regex的方法:

public List<string> getIP(string myString)
    {
        List<string> myString = new List<string>();
        // use Regex.Matches to get all the string parts that match for an IP adress
        MatchCollection matchs = Regex.Matches(input, @"\d+\.\d+\.\d+\.\d+", RegexOptions.IgnoreCase);

        //collect all the strings that matches
        foreach (Match match in matchs)
        {
            output.Add(match.Value);
        }

        //finaly! return the result as a list
        return output;
    }

你只需给你的字符串输入这个函数,它将返回其中的所有ip地址 您可以使用他们的索引访问。 希望有所帮助。