正则表达式忽略模式

问题描述:

我有一些注释,标记文本。括号'('和')'或'['和']'用于确定注释的部分内容(在正常文本中就像这句话一样)。我想对它执行一个正则表达式来搜索输入内容,但是它应该忽略所有注释。正则表达式忽略模式

的问题是:

  • ,他们可以在任何地方(我不知道在哪里,有多少)
  • 我不能轻易剥夺他们出现(进行替换,正则表达式来杀死所有appearences ),因为我需要在原文进行我的搜索正则表达式后才知道索引和长度
  • 它必须尽可能快地成为一个巨大的输入文本

注释不能嵌套编辑,像“123(Hello(World))”不会出现。如果注释括号是字符串的一部分(用引号引起来),它们是文本的一部分,因此不包含注释。

这里有一个例子:

Input Text: "Hello, my (real) name is John. I worked in England (near London) on a real german restaurant.". 

Search Regex: "my.*?real" 

Output: "my (real) name is John. I worked in England (near London) on a real" (index=7, length=67) 

什么是解决它的最好方法?

+0

我想你可以尝试更换一些异国情调的占位符,就像#等于lenght与注释,之后searh文本的所有注释。例如:(真正的)替换###### – Frank59 2013-02-28 17:18:50

+0

我不知道他们在输入的位置,括号内有多少和什么。我只知道“一切都在括号中具有不容忽视。例如模式‘AC’必须匹配输入‘A(B)C’ – 0xDEADBEEF 2013-02-28 17:20:16

+0

您可以使用正则表达式搜索的注释,之后更换上占位 – Frank59 2013-02-28 17:21:58

不知正则表达式是不是你在这种情况下的朋友。特别是因为你想要最快的算法,也许你应该实现这个状态机。

在本质上,通过串一个字符时间翻录并保持匹配注释定界符的堆叠。只要你不在注释中,也要注意你想要匹配的字符串。

澄清的问题:你能假设你要搜索的文本是一个固定的文字?你关心空白的数量吗?我在问,因为一旦你消除了“注释”问题,你可能不需要RegExes的全部功能来完成剩余的搜索。

您可以使用

my.*?real(?![^(\[]*[\)\]]) 

试试这个下面的代码也可能是我们

public string output { get; set; } 

    string input="Hello, my [FirstName] name is John. I worked in England [nearLondon] on a real german restaurant.". 
    static readonly Regex re = new Regex(@"\{([^\}]+)\}", RegexOptions.Compiled); 

    StringDictionary fields = new StringDictionary(); 
    fields.Add("FirstName", yourname); 
    fields.Add("nearLondon", yournearLondon); 

    output = re.Replace(input, delegate(Match match) 
     { 
      return fields[match.Groups[1].Value]; 
     }); 

string source = 
      @"Hello, my (real) name is John. I worked in England (near London) on a real german restaurant."; 

     Regex regex=new Regex(@"\(.*?\)"); 

     MatchCollection matchCollection= regex.Matches(source); 

     foreach (Match match in matchCollection) 
     { 
      source = source.Replace(match.Groups[0].Value, GetPlaceholderString(match.Groups[0].Length)); 
     } 
     MessageBox.Show(source); 

其中GetPlaceholderString使plactholder字符串长度所需。

在此之后,你可以搜索你的字忽略,所有anotations