0

有没有办法在这样的字符串中进行替换?(这是简化的例子)

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

2 回答 2

1

你想要这样的东西吗......

/// <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

于 2012-08-29T09:02:43.280 回答
0

听起来像你想\r\n \" \r\n\r\n \" \n

input = input.Replace("\r\n \" \r\n", "\r\n \" \n");
于 2012-08-29T08:16:28.787 回答