gpt4 book ai didi

C# string.remove 和 Regex.Match

转载 作者:太空宇宙 更新时间:2023-11-03 17:53:43 24 4
gpt4 key购买 nike

我有一个正在搜索的文本文件,我想跳过每一行的前 10 个字符。

每一行都以 [10:16:01] 开头,这是我想跳过的内容,我想找到该行中的下一个数字并将这些数字加在一起。

这就是我到目前为止设法做到的

foreach (string line in lines)
{
string a = line.Remove(0, 10);
if (a.Contains("whateverimsearchingfor"))
{

string resultString = Regex.Match(a, @"\d+").Value;
int result = Int32.Parse(resultString);

total += result
}

提前致谢!

抱歉,当我尝试构建时,我得到:

ArgumentOutOfRangeException was unhandled index and count must refer to a location within the string

它指向字符串 a = line.remove(0, 10)

希望这就足够了。

最佳答案

问题似乎是文件中的某些行太短,因此 line.Remove 将失败,因为字符串中没有足够的字符可以删除。使用此代码跳过任何太短而无法处理的行:

foreach (string line in lines)
{
if (line.Length < 10)
continue;

string a = line.Remove(0, 10);
...
}

或者这个,如果你在你发布的代码下面有其他处理,即使行太短你也想运行:

foreach (string line in lines)
{
if (line.Length >= 10)
{
string a = line.Remove(0, 10);
...
}
}

关于C# string.remove 和 Regex.Match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17307497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com