2012-08-29 46 views
0

有沒有辦法在像這樣的字符串中進行替換? (這是簡化的例子)僅在外部字符串中替換C#字符串

string input = "INSERT INTO blah VALUES \" blah blah \r\n \" \r\n (here can be anything like several new lines and \t tabs) INSERT INTO blah VALUES \" blah blah \r\n \" \r\n"; 

input.Replace("\r\n", "\n"); // this is just example, it doesn't work the way I need it 

// and the output would look like this: 
string output= "INSERT INTO blah VALUES \" blah blah \r\n \" \n INSERT INTO blah VALUES \" blah blah \r\n \" \n"; 

那麼它只會替換SQL命令之外的新行?這可以使用正則表達式安全地實現嗎?

編輯:替換必須可能用\ r \ n來實現\ n可能有更多的SQL命令之間。這些命令沒有精確分開。

編輯:所以基本的問題是 - 我如何只在外部字符串取代?

string = "outer string \"inner string\" outer string \"inner string\" outer string" 
+4

如果您使用SQL語句,我強烈建議使用SqlParameters:http://www.dotnetperls.com/sqlparameter – RvdK

+4

Replace會返回新的字符串,所以代碼應該看起來像'input = input.Replace(「\ r \ n」 ,「\ n」);' – Reniuz

回答

1

你想是這樣的,以取代\r\n \" \r\n ....

/// <summary> 
/// Regular expression built for C# on: Wed, Aug 29, 2012, 09:56:25 AM 
/// Using Expresso Version: 3.0.4334, http://www.ultrapico.com 
/// 
/// A description of the regular expression: 
/// 
/// [1]: A numbered capture group. [(?<counter>").*?(?<-counter>").*?(?(counter)(?!))] 
///  (?<counter>").*?(?<-counter>").*?(?(counter)(?!)) 
///   [counter]: A named capture group. ["] 
///    " 
///   Any character, any number of repetitions, as few as possible 
///   Balancing group. Remove the most recent [counter] capture from the stack. ["] 
///    " 
///   Any character, any number of repetitions, as few as possible 
///   Conditional Expression with "Yes" clause only 
///    Did the capture named [counter] match? 
///    If yes, search for [(?!)] 
///     Match if suffix is absent. [] 
///      NULL 
/// \r\n 
///  Carriage return 
///  New line 
/// 
/// 
/// </summary> 
Regex regex = new Regex(
     "((?<counter>\").*?(?<-counter>\").*?(?(counter)(?!)))\\r\\n", 
    RegexOptions.CultureInvariant 
    | RegexOptions.Compiled 
    | RegexOptions.Singleline 
    ); 

string input = "INSERT INTO blah VALUES \" blah blah \r\n \" \r\n (here can be anything like several new lines and \t tabs) INSERT INTO blah VALUES \" blah blah \r\n \" \r\n"; 

string output output=regex.Replace(input,"$1\n"); 

(?<counter>").*?(?<-counter>").*?(?(counter)(?!))的效果是匹配只有平衡"個字符才能找到引號外的\ r \ n

+0

太棒了!非常感謝你。 –

0

聽起來像你想\r\n \" \n

input = input.Replace("\r\n \" \r\n", "\r\n \" \n"); 
+0

sql命令之間的新行數是小數點且命令可以不同 –