2010-04-14 81 views
0

我有一个纯文本文件是这样的:正则表达式向下填充

Ford\tTaurus 
    F-150 
    F-250 
Toyota\tCamry 
    Corsica 

换句话说,两级层次结构中的第一个孩子是在同一行作为家长,但孩子以后在下面的行中,区别于由双空格前缀作为父节点(上面的\t表示文本中的文字标签)。

我需要转换到这种使用正则表达式:

Ford\tTaurus 
Ford\tF-150 
Ford\tF-250 
Toyota\tCamry 
Toyota\tCorsica 

所以,我需要捕获父(之间的文本\ r \ n和\ t不\ S \ S开始),并应用在任何\r\n\s\s的中间发现,直到下一个父母。

我有一种感觉,这可以用某种嵌套组完成,但我认为我需要更多的咖啡因或其他东西,似乎无法解决这种模式。

(使用.NET与IgnoreWhitespace关闭,多行关闭)

回答

3

要使用正则表达式这有什么特别的原因吗?这里的代码做什么,我想你想,也懒得锻炼的正则表达式:

using System; 
using System.IO; 

class Test 
{ 
    static void Main(string[] args) 
    { 
     string currentManufacturer = null; 

     using (TextReader reader = File.OpenText(args[0])) 
     using (TextWriter writer = File.CreateText(args[1])) 
     { 
      string line; 
      while ((line = reader.ReadLine()) != null) 
      { 
       string car; 
       if (line.StartsWith(" ")) 
       { 
        if (currentManufacturer == null) 
        { 
         // Handle this properly in reality :) 
         throw new Exception("Invalid data"); 
        } 
        car = line.Substring(2); 
       } 
       else 
       { 
        string[] bits = line.Split('\t'); 
        if (bits.Length != 2) 
        { 
         // Handle this properly in reality :) 
         throw new Exception("Invalid data"); 
        } 
        currentManufacturer = bits[0]; 
        car = bits[1]; 
       } 
       writer.WriteLine("{0}\t{1}", currentManufacturer, car); 
      } 
     } 
    } 
} 
+0

感谢Jon ...我有一个Intranet应用程序,通过应用基于输入源从数据库表中提取的RegEx替换,从各种数据源擦除文本。这使我能够在不重新编译的情况下处理来自数十个来源的乱序数据。该应用程序可以调用自定义函数,但是我会尽可能避免使用该功能。看起来我可能在这里没有选择。 – richardtallent 2010-04-15 04:33:34

+0

@richardtallent:嗯,这可能是可能的 - 但是,如果没有正则表达式巫术,我觉得它更简单了:) – 2010-04-15 05:26:29

0

这是简单的(但不是明智或快速)使用正则表达式来实现这一目标。

更换

(?<=^(Ford\t|Toyota\t).*?)^ 

$1。确保^$匹配在行首/末尾,.匹配换行符。