2011-09-24 15 views
-1

我有一個dic.txt數據(文本)文件。該文件的內容如下:正則表達式的方法來讀取TXT文件

(watyai) w a t^ j a j^ 
(noi) n @@ j^ 
(mai) m a j^ 

我想讀這些項目,並分析它們是這樣的:

watyai 
noi 
mai 

w a t^ j a j^ 
n @@ j^ 
m a j^ 

我該如何使用C#做到這一點?

+0

該文件有多大?文件的格式是否被很好地指定?性能是一個問題嗎? –

回答

1

你可以使用正則表達式:

Regex regex = new Regex(@"^\(([^)]+)\)\s+(.+)$"); 

string[] lines = File.ReadAllLines(pathToFile); 
foreach (string line in lines) 
{ 
    Match match = regex.Match(line); 
    if (match.Success) 
    { 
     string key = match.Groups[1].Value; 
     string value = match.Groups[2].Value; 
    } 
} 
0

下面的正則表達式將提取的第一個詞從它的支架,並閱讀其他一切(忽視空格)周圍,直到行結束

string[] dic_lines = File.ReadAllLines("path_to_dic_file.dic"); 
List<string> l_group1 = new List<string>(); 
List<string> l_group2 = new List<string>(); 

foreach(subjectString in dic_lines) 
{ 
    Regex regexObj = new Regex(@"(\(.*?\))\s*(.*)\s*"); 
    Match match = regexObj.Match(subjectString); 
    if (matchResults.Success) { 
     l_group1.Add(match.Groups[1].Value); 
     l_group2.Add(match.Groups[2].Value); 
    } 
} 

File.WritaAllLines("outputfile.txt", l_group1); 
File.AppendAllLines("outputfile.txt", l_group2); 
-1

一正則表達式:

(?<=\()\b\w+\b(?=\)) 

二正則表達式:

(?<=(\(\w+\)(\s{3})))(.*) 
+1

請提供問題的完整答案。這個問題是C#特有的,並要求用C#編寫代碼,而不僅僅是正則表達式。 –