2017-10-17 178 views
0

我需要找到字符串作爲文件如下:獲取使用正則表達式的文本和行號

_["Some text"]; 

or 

_.Plural(1, "Some text", "Some text plural); 

我循環使用文件的文本行:

using (StreamReader reader = File.OpenText(file)) { 

    String line; 

    while ((line = reader.ReadLine()) != null) { 

    }   
}   

在每一行,我需要得到:

"Some text" 

OR

"Some text", "Some text plural" 

而在這兩種情況下,我需要爲每個實例獲取文件內的行號。

如何處理正則表達式?

+0

正則表達式是難溶適合對這種任務;爲什麼你必須使用一個? –

+0

你不需要正則表達式....你可以做somevar.contains(「一些文本」)...或類似的東西。 – Kixoka

回答

0

使用從這些SO職位圖案和邏輯:
https://stackoverflow.com/a/171483/1634205
https://stackoverflow.com/a/4892517/1634205

而繼這個教程:
https://www.dotnetperls.com/regex-file

嘗試這種情況:

static void Main(string[] args) 
    { 
     Regex pattern = new Regex("\"(.*?)\""); 

     string file = @"C:\where\your-file\is\file.txt"; 

     using (StreamReader reader = File.OpenText(file)) 
     { 
      string line; 

      while ((line = reader.ReadLine()) != null) 
      { 
       foreach (Match match in pattern.Matches(line)) 
       { 
        Console.WriteLine(match.Value); 
       } 
      } 
     } 

     Console.ReadLine(); 
    }