【问题标题】:C# string replace in outer string only仅在外部字符串中替换 C# 字符串
【发布时间】:2012-08-29 08:07:52
【问题描述】:

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

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"

【问题讨论】:

  • 如果你将它用于SQL语句我强烈推荐SqlParameters:dotnetperls.com/sqlparameter
  • Replace 返回新字符串,因此代码应类似于 input = input.Replace("\r\n", "\n");

标签: c# string replace newline


【解决方案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");

(?&lt;counter&gt;").*?(?&lt;-counter&gt;").*?(?(counter)(?!)) 的作用是只匹配平衡的" 字符,以便只找到引号外的\r\n

【讨论】:

  • 太棒了!非常感谢。
【解决方案2】:

听起来像你想用\r\n \" \n替换\r\n \" \r\n

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

【讨论】:

  • sql命令之间的换行数不规则,命令可以不同
猜你喜欢
  • 2020-03-04
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-30
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
相关资源
最近更新 更多