0

I have string file with content like this

string a = "12,1,______,_,__;1,23,122;"

I want to grab only this integer value 23. Problem is that this conntent is dynamic and I it's lenght can be changed, so this string a can easily be in the next iteration like

string a = "12,1,______,_,__;11,2,1;"

In this case I would grab integer 2.

4

5 回答 5

3

如果结构始终相同,则:

拆分字符串,然后抓取最后一个元素。

var array1 =  a.Split(';');

// check the array length if it's needed to avoid 
// IndexOutOfRangeException exception
var array2 =  array1[1].Split(',');

var yourNumber = array2[array2.Length - 2]

字符串拆分

于 2013-08-12T07:39:40.167 回答
2

忽略错误检查一分钟,这将起作用:

string a = "12,1,______,_,__;11,2,1;"
int i = Int32.Parse(String.Split(',')[5])

如果这是您将要走的路线,则应格外小心以验证您的输入。检查从 中返回的数组的长度Split,并验证第 5 个值是否确实可以解析为int

于 2013-08-12T07:38:56.390 回答
1

试试这个正则表达式:

(?<=;\d*,)\d*(?=,\d*;)

示例用法:

class Program
{
    static void Main(string[] args)
    {
        string a = "12,1,______,_,__;1,23,122;";
        var regex = new Regex(@"(?<=;\d*,)\d*(?=,\d*;)");
        Console.WriteLine(regex.Match(a).Value);            
        a = "12,1,______,_,__;11,2,1;";
        Console.WriteLine(regex.Match(a).Value);
    }
}
于 2013-08-12T07:37:35.463 回答
1

尝试这个:

var number = a.split(",")[5];
于 2013-08-12T07:38:48.030 回答
1

另一种选择是将文本拆分为数组(如果它们具有相同的模式):

var output = a.Split(",;".ToCharArray());
var value = output[theIndex]; // get the index you want
于 2013-08-12T07:41:56.880 回答