2009-12-22 45 views
0

嗨我有一個困難的正則表達式問題,我已經嘗試過,並有一個部分的解決方案,但還沒有得到完美的工作。從本質上講,我要解析的文件是在大綱格式像這樣:正則表達式函數幫助

1. HEY BUDDY 
1.A. Your the best 
1.A.1 And i know 
1.A.2. this because 
1.A.3 it is 
1.A.4. the 
1.A.5. truth i 
1.A.6. tell ya. 
1.B. so anyway 
1.B.1. one two 
1.B.2 three four! 
2. i have 
2.A. many numbers 
2.A.1. hahaha 
2.A.1.A. 3.2 ppl 
2.A.1.B. are in 
2.A.1.C my head. 
2.A.1.D. yes exactly 
2.A.2. 3.21 
2.A.3. if you dont 
2.A.4 trust me 
2.B then 
2.B.1. youre 
2.B.2.soo wrong 
2.C. its not 
3. even funny. 
3.A. but it 
3.B. kind of 
3.C. is a little 
4. bit i 
4.A. believe. 
4.A.1. talk to me 
4.A.2. more about 
4.B. these ppl 
4.B.2. in your head. 

這是我的測試文檔...我需要找到每個新的「子彈」的這個文件中,然後保存他們之間的文本並做更多的計算。所有我沒有想到的是如何使用正則表達式精確地識別不同的大綱數字。 (我知道這可能是其他方式,然後正則表達式,但我正在學習正則表達式的過程中,我有我的想法設置這樣做)我現在想出的是這樣的:

(\b)(([1-9][0-9]?)(\.))([A-Z])?((\.)([1-9][0-9]?)((\.)([A-Z]))?)*(\.)?(\b) 

問題在於它沒有識別出1.,2.,3.或4.,並且它正在拾取「3」。從文本中的3.2和3.21開始。 (是的,我會在這樣的文字中加倍)大綱的格式始終是#.AZ。#。AZ。#。AZ ...以及數字永遠不會高於99.

感謝您幫幫我。

回答

1
^[\d\w\.]+ [^\n]+$ 

解釋:「行啓動:任何數字+字符+圓點組合,其次是空間,任何非換行字符的組合:行結束」

有想法,你會當你在你的代碼中寫這個正則表達式時需要添加另一個斜槓。

The Pattern class documentation極其有用即使您使用正則表達式進階。

1

Bozho的解決方案只適用於您的特定示例文檔,並且如果行中沒有以您想匹配的模式開頭的行,將會生成大量錯誤匹配。這裏有一個更具體的解決方案:

^(\d{1,2}\.([A-Z]\.)?){1,2}\s 

這裏是如何使用它:

using System; 
using System.IO; 
using System.Text.RegularExpressions; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     using (var f = File.OpenText("input.txt")) 
     { 
      while (true) 
      { 
       string line = f.ReadLine(); 
       if (line == null) break; 
       Match match = Regex.Match(line, @"^(\d{1,2}\.([A-Z]\.)?){1,2}\s"); 
       if (match.Success) 
       { 
        Console.WriteLine(match.Value); 
        string result = match.Value.Substring(0, match.Value.Length - 2); 
        string[] array = result.Split('.'); 
        // .. 
       } 
      } 
     } 

    } 
}