2009-12-22 66 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('.'); 
        // .. 
       } 
      } 
     } 

    } 
}