C#解析一行并提取给定行中“”“中包含的所有整数

时间:2016-06-18 19:47:11

标签: c# .net visual-studio

我正在处理一个文件(可能是cs,xml或any),我需要提取格式为“123”的字符串。 “”中包含的任何数字都可以是1到10000。

这是我使用的,但它没有返回多个匹配    预期输出:“828”,“9999”

我的代码:

var match = Regex.Match(line,"\"\\d*\"");

                if (match.Success)
                {
                    lstStringIds.Add(match.Value);                    
                }

我的比赛总是只有一场比赛。我如何获得多个整数匹配?

4 个答案:

答案 0 :(得分:1)

Test it:

string myline = @"""123"" ""5587"" ""9"" ""7896""";

var resultlist = Regex.Matches(myline, @"\d+").Cast<Match>()
                .Select(x=>x.Value).ToList();

Returns:

123 
5587 
9 
7896 

For further information, please see: Regex.Matches Method (String, String, RegexOptions)

答案 1 :(得分:1)

Non-LINQ approach.

string line = "\"802\" and \"1009\" and \"1.0\" and \"10001\" and \"10000\"";
var lstStringIds = new List<String>();
var match = Regex.Match(line, "\"(?:\\d{1,4}|10000)\"");
while (match.Success)
{
    lstStringIds.Add(match.ToString());
    match = match.NextMatch();
}

Returns: "802" "1009" "10000"

答案 2 :(得分:0)

for (int count = 0; count < input_string.Length; count ++)
{
    if ((input_string[count] == //first number) && (input_string[count + 1] == //second number) && (input_string[count + 2] == //third number))
    {
        lstStringIds.Add(input_count[count]);
        // [count + 1]
        // [count + 2]
    }
}

That's how I would cycle through a list to find substrings that are equal to a condition. Let me know if that wasn't helpful or wasn't what you were looking for.

答案 3 :(得分:0)

    string line = "\"100\", \"200\" ";
    var match = Regex.Match(line, "(\"\\d*\")");
    ArrayList al = new ArrayList();

    while(match.Success && match != null)
    {
        al.Add(match.Value);
        match = match.NextMatch();
    }