c# - 在文档中查找最高数字的最快方法

标签 c# winforms

我有这样的文件:

[...]
UTS+48:::{7}:{8}+{9}'
UTB+454343::34343+{10}-{12}'
[...]

在我的表单中选择文件后,我将整个文件读入一个字符串。现在,我需要找到这些括号 {} 之间的最大数字。最好的解决方案是什么?我已经解决了这个问题,但我认为我的解决方案并不是最好的。我正在考虑使用一些正则表达式,但我不知道如何正确使用它。

这是我的解决方案:

private int GetNumberOfParameters(string text)
{
    string temp = File.ReadAllText(text);
    string number = String.Empty, highestNumber = String.Empty;
    bool firstNumber = true;
    for (int i = 0; i < temp.Length; i++)
    {
        if (temp[i].Equals('{'))
        {
            int j = i;
            j++;
            while (!temp[j].Equals('}'))
            {
                number += temp[j];
                j++;
            }

            if (firstNumber)
            {
                highestNumber = number;
                number = String.Empty;
                firstNumber = false;
            }
            else if (Int16.Parse(number) > Int16.Parse(highestNumber))
            {
                highestNumber = number;
                number = String.Empty;
            }
            else
            {
                number = String.Empty;
            }

        }
    }
    if (highestNumber.Equals(String.Empty))
        return 0;
    else
        return Int16.Parse(highestNumber);
}

最佳答案

您可以使用以下正则表达式提取 {} 括号之间的数字字符串。

(?<={)\d+(?=})

Regular expression visualization

然后将提取的字符串转换为数字并找到最大值。

示例代码:

string s = "{5} + {666}";
long max = Regex.Matches(s, @"(?<={)\d+(?=})")
                .Cast<Match>()
                .Select(m => long.Parse(m.Value))
                .Max();

关于c# - 在文档中查找最高数字的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24179029/

相关文章:

c# - 拉绳粗体和普通文本

c# - PSD 文件未正确调整大小

c# - DataGridView DataBindingComplete 事件的替代方案

c# - 确定鼠标悬停在 FastColoredTextBox 中的哪个单词上?

C# RSS 聚合,如何以编程方式格式化文本

c# - ASP.NET MVC 5 异步上下文管理

c# - Access 数据库引擎的优点和缺点。 SQLite 之后的生活

c# - 使用 SqlBulkCopy 插入 GUID

c# - 列表框更新,焦点位于列表框中的最后一行

c# - 如何禁用双击winform按钮?