2013-02-28 138 views
2

我有一些註釋,標記文本。括號'('和')'或'['和']'用於確定註釋的部分內容(在正常文本中就像這句話一樣)。我想對它執行一個正則表達式來搜索輸入內容,但是它應該忽略所有註釋。正則表達式忽略模式

的問題是:

  • ,他們可以在任何地方(我不知道在哪裏,有多少)
  • 我不能輕易剝奪他們出現(進行替換,正則表達式來殺死所有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

回答

0

不知正則表達式是不是你在這種情況下的朋友。特別是因爲你想要最快的算法,也許你應該實現這個狀態機。

在本質上,通過串一個字符時間翻錄並保持匹配註釋定界符的堆疊。只要你不在註釋中,也要注意你想要匹配的字符串。

澄清的問題:你能假設你要搜索的文本是一個固定的文字?你關心空白的數量嗎?我在問,因爲一旦你消除了「註釋」問題,你可能不需要RegExes的全部功能來完成剩餘的搜索。

0

您可以使用

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

試試這個下面的代碼也可能是我們

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]; 
     }); 
0
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