簡體   English   中英

C#string.remove和Regex.Match

[英]c# string.remove & Regex.Match

我有一個正在搜索的文本文件,我想跳過每行中的前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是未處理的索引,並且計數必須引用字符串中的位置

它指向字符串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);
        ...
    }
}

如果只想處理帶數字的行:

foreach (string line in lines.Where(l => l.Length >= 10))

這將跳過少於10個字符的行。

您正在string.Remove上收到ArgumentOutOfRangeExceptionstring.Remove原因( MSDN ):

startIndex或count均小於零。 -或-startIndex加count指定此實例之外的位置

我看到您已經接受了答案,但是無論如何我都會把它留在這里。

您的問題有點模棱兩可,聽起來正則表達式不是您唯一的選擇。 如果只想始終跳過前10個字符,則可以使用子字符串並跳過正則表達式。 在此示例中查看子字符串。

這是一個簡單的例子:

String input = "0123456789Hello World";
String sub = input.Substring(10, input.Length - 10);
Console.WriteLine(sub);

第一個參數是您要開始子字符串的位置,第二個參數是您要從原始字符開始的字符數。

在您的代碼中:

foreach(String line in lines)
{
     String sub = line.Substring(10, line.Length - 10);
}

編輯:

或者,您可以使用更簡單的Substring調用。 該調用將簡單地返回給定索引之后的整個字符串。

foreach(String line in lines)
{
    String sub = line.Substring(10);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM