有没有办法在像这样的字符串中进行替换? (这是简化的例子)
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 \ n \ n \ n \ n在SQL命令之间可能会有更多的替换。命令没有精确分离。
编辑:所以基本问题是 - 如何仅替换外部字符串?
string = "outer string \"inner string\" outer string \"inner string\" outer string"
答案 0 :(得分: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
答案 1 :(得分:0)
您听起来像要将\r\n \" \r\n
替换为\r\n \" \n
input = input.Replace("\r\n \" \r\n", "\r\n \" \n");