c# - 删除括号内的空格(引号内的文本除外)

标签 c# .net regex

我正在寻找一个正则表达式,它可以删除匹配括号之间的空格,即 ()除了引号内的空格('")方括号内。

我目前有正则表达式 \s+(?=[^(]*\)),它会删除括号之间的所有空格。当引号中有空格时也是如此。

// My input
do something with(in = 1, text='some text with spaces' , text2="also has spaces")

// My current output
do something with(in=1,text='sometextwithspaces',text2="alsohasspaces")

// My desired output
do something with(in=1,text='some text with spaces',text2="also has spaces")

此外:

  • 引号只能出现在括号内
  • ' ' 文本中可以有 ":text='text with "inside',不带\ 转义字符。
  • " " 文本中可以有 ':text="text with ' inside",不带\ 转义字符。
  • 字符串中引号前转义字符:text='This is\"not There'

我知道有很多关于正则表达式模式的问题,但我找不到一个能解决问题的方法。在我尝试过的许多事情中,期望只找到 ( 直到 '"\s+ 之间的内容(?=[^("]*[\)"]),但仍然会在 "" 之间找到空格。

有人能指出我正确的方向吗?

最佳答案

好吧,由于您有两种类型的引用,"',您必须处理引用的引用:

  abc"def pqr' ijk" "klm ' xyz"

请注意,两个撇号都被引用,这就是为什么不起作用。与括号相同。我怀疑是否 简单的正则表达式可以在这里提供帮助,但有限状态机可以:

private static string RemoveSpaces(string value) {
  if (string.IsNullOrEmpty(value))
    return value;

  bool inQuotation = false;
  bool inApostroph = false;
  int bracketCount = 0;
  int escapeCount = 0;
  StringBuilder result = new StringBuilder(value.Length);

  foreach (char c in value) {
    if (inQuotation) {
      result.Append(c);
      inQuotation = c != '"' || (escapeCount % 2 != 0);
    }
    else if (inApostroph) {
      result.Append(c);
      inApostroph = c != '\'' || (escapeCount % 2 != 0);
    }
    else {
      if (c != ' ' || bracketCount <= 0)
        result.Append(c);

      if (c == '(')
        bracketCount += 1;
      else if (bracketCount == ')')
        bracketCount -= 1;

      inQuotation = c == '"' && (escapeCount % 2 == 0);
      inApostroph = c == '\'' && (escapeCount % 2 == 0);
    }

    escapeCount = c == '\\' ? escapeCount + 1 : 0;
  }
  return result.ToString();
}

演示:

string test =
  @"do something with(in = 1, text='some text with spaces' , text2=""also has spaces"")";

Console.WriteLine(RemoveSpaces(test));

结果:

do something with(in=1,text='some text with spaces',text2="also has spaces")

关于c# - 删除括号内的空格(引号内的文本除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63474283/

相关文章:

c# - 如何指定用于 WebClient 类的 SSL 协议(protocol)

javascript - 简单的正则表达式在 Javascript 中不起作用

php - 如何在德语元音变音 [äöü] 上 preg_match_all?

与 Arduino 的 C# 串行通信

c# - 使用 .Net 如何使用 Sort 方法对数组进行反向排序,即从 Z 到 A?

c# - 无法验证 OWIN OpenIdConnect 中间件 IDX10311 nonce

c++ - 如何正确链接 boost 正则表达式?

c# - 根据 AD 验证凭据

c# - .Net 4 中的多线程 C# 队列

c# - 在 .NET 4.7 中使用长路径时出现 DirectoryNotFoundException